private synchronized void generatePartitionMapsAndSwitch(List<ReplicaId> addedReplicas,
        List<ReplicaId> removedReplicas) {
      String dcName = addedReplicas.isEmpty() ? removedReplicas.get(0).getDataNodeId().getDatacenterName()
          : addedReplicas.get(0).getDataNodeId().getDatacenterName();
      logger.info("Re-populating partition-selection related maps because replicas are added or removed in {}", dcName);
      // condition here, remember this method can be invoked by multiple threads (synchronize this method?)
      Collection<? extends PartitionId> partitions = clusterManagerQueryHelper.getPartitions();
      Collection<PartitionId> partitionsInCluster = getFilteredPartitions(partitions);

      Map<String, SortedMap<Integer, List<PartitionId>>> partitionSortedByReplicaCount =
          new TreeMap<>(String.CASE_INSENSITIVE_ORDER);
      Map<PartitionId, List<ReplicaId>> partitionAndLocalReplicas = new HashMap<>();
      populatePartitionAndLocalReplicaMaps(partitionsInCluster, partitionSortedByReplicaCount,
          partitionAndLocalReplicas, localDatacenterName);
      rwLock.writeLock().lock();
      // switch references to newly generated maps
      try {
        allPartitions = partitionsInCluster;
        partitionIdsByClassAndLocalReplicaCount = partitionSortedByReplicaCount;
        partitionIdToLocalReplicas = partitionAndLocalReplicas;
      } finally {
        rwLock.writeLock().unlock();
      }
      logger.info("Partition-selection related maps updated after replica changes in {}", dcName);
    }
Generate new partition-selection related maps and switch current maps to new ones. This method should be synchronized
because it can be invoked by cluster change handlers in different dcs concurrently. We need to ensure one dc has
completely updated in-mem data structures and then move on to the next.
@param addedReplicas a list of replicas are newly added in cluster
@param removedReplicas a list of replicas have been removed from cluster.
ambry-clustermap/src/main/java/com/github/ambry/clustermap/ClusterMapUtils.java