All Downloads are FREE. Search and download functionalities are using the official Maven repository.

io.tarantool.driver.utils.CyclingIterator Maven / Gradle / Ivy

Go to download

Tarantool Cartridge driver for Tarantool versions 1.10+ based on Netty framework

There is a newer version: 0.14.0
Show newest version
package io.tarantool.driver.utils;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * This iterator is lock-free and loops infinitely over a collection.
 *
 * @author Alexey Kuzin
 * @author Sergey Volgin
 */
public class CyclingIterator implements Iterator {

    private final List items;
    private final int size;
    private final AtomicInteger position = new AtomicInteger(0);

    /**
     * Basic constructor.
     *
     * @param items collection to iterate over
     */
    public CyclingIterator(Collection items) {
        this.items = Collections.synchronizedList(new ArrayList<>(items));
        this.size = items.size();
    }

    @Override
    public boolean hasNext() {
        return size > 0;
    }

    @Override
    public T next() {
        return items.get(position.getAndUpdate(p -> (p + 1) % size));
    }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy