Search code examples
javamultithreadingsynchronizationproducer-consumer

Single Item Producer-Consumer. Which datastructure can I use in Java?


I want have a Producer Consumer Problem where only the newest Item shall be consumed. This problem may have a different name, but I couldn't figure it out!

The producer thread(s) produce elements in a non-blocking fashion by overriting any old items. The single consumer thread should wait for an element to be created and consume it.

I thought about using a blocking queue but the java implementation does not allow for overriding old elements. A circular buffer (like from the commons libary) doesn't work either because its not blocking for the consumer.

Is there a datastructure that serves this purpose or do I need to find a better way?

It might also be possible to solve this with low level synchronization tools like locks but I couldn't figure out how to do it.


Solution

  • There is no need for a special data structure. Just use the methods available in Object. They are quite good in this situation, because the blocking consumer:

    class ItemHolder<T> {
        private T item;
        public synchronized void produce(T item) {
            this.item = item;
            notify();
        }
        public synchronized T consume() {
            while (item == null) {
                wait();
            }
            T result = item;
            item = null;
            return result;
        }
    }