private void rebalance ( ) { boolean rebalanced = false ; for ( ElectionState election : elections . values ( ) ) { // Count the total number of primaries for this election's primary. int primaryCount = election . countPrimaries ( election . primary ) ; // Find the registration with the fewest number of primaries. int minCandidateCount = 0 ; for ( Registration candidate : election . registrations ) { if ( minCandidateCount == 0 ) { minCandidateCount = election . countPrimaries ( candidate ) ; } else { minCandidateCount = Math . min ( minCandidateCount , election . countPrimaries ( candidate ) ) ; } } // If the primary count for the current primary is more than that of the candidate with the fewest // primaries then transfer leadership to the candidate. if ( minCandidateCount < primaryCount ) { for ( Registration candidate : election . registrations ) { if ( election . countPrimaries ( candidate ) < primaryCount ) { PrimaryTerm oldTerm = election . term ( ) ; elections . put ( election . partitionId , election . transfer ( candidate . member ( ) ) ) ; PrimaryTerm newTerm = term ( election . partitionId ) ; if ( ! Objects . equals ( oldTerm , newTerm ) ) { notifyTermChange ( election . partitionId , newTerm ) ; rebalanced = true ; } } } } } // If some elections were rebalanced, reschedule another rebalance after an interval to give the cluster a // change to recognize the primary change and replicate state first. if ( rebalanced ) { scheduleRebalance ( ) ; } }
Periodically rebalances primaries .