Friday, December 18, 2009

Vacation: BlockingIterable

I love vacation: a chance to stretch my coding fingers free of work! Here is a code snack I thought of while daydreaming today—enjoy!

public final class BlockingIterable {
    public static <E> Until<E> over(final BlockingQueue<E> queue) {
        return new Until<E>(queue);
    }

    public static class Until<E> {
        private final BlockingQueue<E> queue;

        private Until(final BlockingQueue<E> queue) {
            this.queue = queue;
        }

        public Iterable<E> until(final E poison) {
            return new Iterable<E>() {
                @Override
                public Iterator<E> iterator() {
                    return new Iterator<E>() {
                        private E next = poison;

                        @Override
                        public boolean hasNext() {
                            try {
                                return poison != (next = queue.take());
                            } catch (final InterruptedException e) {
                                currentThread().interrupt();
                                next = poison;
                                return false;
                            }
                        }

                        @Override
                        public E next() {
                            if (poison == next)
                                throw new NoSuchElementException();
                            return next;
                        }

                        @Override
                        public void remove() {
                            throw new UnsupportedOperationException();
                        }
                    };
                }
            };
        }
    }
}
Post a Comment