void changeIndexSegments(List<File> segmentFilesToAdd, Set<Offset> segmentsToRemove) throws StoreException {
    rwLock.writeLock().lock();
    try {
      Offset journalFirstOffset = journal.getFirstOffset();

      TreeMap<Offset, IndexSegment> segmentsToAdd = new TreeMap<>();
      for (File indexSegmentFile : segmentFilesToAdd) {
        IndexSegment indexSegment = new IndexSegment(indexSegmentFile, true, factory, config, metrics, journal, time);
        if (journalFirstOffset != null && indexSegment.getEndOffset().compareTo(journalFirstOffset) > 0) {
          throw new IllegalArgumentException(
              "One of the index segments has an end offset " + indexSegment.getEndOffset()
                  + " that is higher than the first offset in the journal " + journalFirstOffset);
        }
        segmentsToAdd.put(indexSegment.getStartOffset(), indexSegment);
      }

      for (Offset offset : segmentsToRemove) {
        IndexSegment segmentToRemove = validIndexSegments.get(offset);
        if (journalFirstOffset != null && segmentToRemove.getEndOffset().compareTo(journalFirstOffset) >= 0) {
          throw new IllegalArgumentException(
              "End Offset of the one of the segments to remove [" + segmentToRemove.getFile() + "] is"
                  + " higher than the first offset in the journal");
        }
      }

      // first update the influx index segments reference
      inFluxIndexSegments = new ConcurrentSkipListMap<>();
      // now copy over all valid segments to the influx reference, remove ones that need removing and add the new ones.
      inFluxIndexSegments.putAll(validIndexSegments);
      inFluxIndexSegments.keySet().removeAll(segmentsToRemove);
      inFluxIndexSegments.putAll(segmentsToAdd);
      // change the reference (this is guaranteed to be atomic by java)
      validIndexSegments = inFluxIndexSegments;
    } finally {
      rwLock.writeLock().unlock();
    }
  }
Atomically adds {@code segmentFilesToAdd} to and removes {@code segmentsToRemove} from the map of {@link Offset} to
{@link IndexSegment} instances.
@param segmentFilesToAdd the backing files of the {@link IndexSegment} instances to add.
@param segmentsToRemove the start {@link Offset} of {@link IndexSegment} instances to remove.
@throws IllegalArgumentException if any {@link IndexSegment} that needs to be added or removed has an offset higher
than that in the journal.
@throws StoreException if an {@link IndexSegment} instance cannot be created for the provided files to add.
ambry-store/src/main/java/com/github/ambry/store/PersistentIndex.java