class RoundRobinVolumeChoosingPolicy implements VolumeChoosingPolicy {

  @Override
  public HddsVolume chooseVolume(List<HddsVolume> volumes,
      long maxContainerSize) throws IOException {

    // No volumes available to choose from
    if (volumes.size() < 1) {
      throw new DiskOutOfSpaceException("No more available volumes");
    }

    // since volumes could've been removed because of the failure
    // make sure we are not out of bounds
    int nextIndex = nextVolumeIndex.get();
    int currentVolumeIndex = nextIndex < volumes.size() ? nextIndex : 0;

    int startVolumeIndex = currentVolumeIndex;
    long maxAvailable = 0;

    while (true) {
      final HddsVolume volume = volumes.get(currentVolumeIndex);
      // adjust for remaining capacity in Open containers
      long availableVolumeSize = volume.getAvailable()
          - volume.getCommittedBytes();

      currentVolumeIndex = (currentVolumeIndex + 1) % volumes.size();

      if (availableVolumeSize > maxContainerSize) {
        nextVolumeIndex.compareAndSet(nextIndex, currentVolumeIndex);
        return volume;
      }

      if (availableVolumeSize > maxAvailable) {
        maxAvailable = availableVolumeSize;
      }

      if (currentVolumeIndex == startVolumeIndex) {
        throw new DiskOutOfSpaceException("Out of space: "
            + "The volume with the most available space (=" + maxAvailable
            + " B) is less than the container size (=" + maxContainerSize
            + " B).");
      }

    }
  }

}