Search code examples
javaconcurrencyproducer-consumer

How to convert a for-loop into a producer?


There is a SynchronousProducer interface, that supports two operations:

public interface SynchronousProducer<ITEM> {
    /**
     * Produces the next item.
     *
     * @return produced item
     */
    ITEM next();

    /**
     * Tells if there are more items available.
     *
     * @return true if there is more items, false otherwise
     */
    boolean hasNext();
}

Consumer asks the producer if there are more items available and if none goes into a shutdown sequence.

Now follows the issue.

At the moment there is a for-loop cycle that acts as a producer:

for (ITEM item: items) {
  consumer.consume(item);
}

The task is to convert a controlling code into the following:

while (producer.hasNext()) {
  consumer.consume(producer.next())
}

consumer.shutdown();

The question. Given the items: how to write the producer implementing SynchronousProducer interface and duplicating the logic of the for-loop shown above?


Solution

  • If items implements Iterable, you can adapt it to your SynchronousProducer interface like this:

    class IterableProducer<T> implements SynchronousProducer<T> {
    
        private Iterator<T> iterator;
    
        public IterableProducer(Iterable<T> iterable) {
            iterator = iterable.iterator();
        }
    
        @Override
        public T next() {
            return iterator.next();
        }
    
        @Override
        public boolean hasNext() {
            return iterator.hasNext();
        }
    }