1

I have a list with objects and I need to iterate thru the list forever while items are getting removed or getting added. This all should happen in a runnable thread. What I want is that the iterating never stops while still being able to add new objects to it, and remove the finished ones.

  • I want to add new objects from outside from the while(true) thread.
  • I want to remove items in the while(true) thread.
  • It's like an FIFO but Dynamic. Or like an queue which never stops.
  • If the list is empty, it has to wait for new objects.

Is this possible in Java?

3
  • You want a queue? We have queues. Commented Mar 1, 2018 at 17:43
  • 1
    Use a LinkedBlockingQueue. It will block Commented Mar 1, 2018 at 17:47
  • 1
    Agree with Johannes, use LinkedBlockingQueue. Commented Mar 1, 2018 at 18:03

1 Answer 1

2

You are describing the Producer / Consumer pattern. Java has thread safe ways to achieve this. The easiest would be to use java.util.concurrent.BlockingQueue<E>

The way to use it is to share the BlockingQueue between a Consumer (thread) and one or more Producer threads. The Consumer blocks with the method E Queue.take(). The clients add to the Queue with method Queue.offer(E).

First create the BlockingQueue:

BlockingQueue<MyObject> myQueue = new LinkedBlockingQueue<MyObject>(int capacity);

The server thread will look something like this:

    BlockingQueue<MyObject> myQueue;
    // A constructor which receives the BlockingQueue object

    // Main Loop
    boolean isInterrupted = false;

    while(!isInterrupted) {
        try {
            MyObject object = myQueue.take();   // Will block
            // Process object
        } catch (InterruptedException e) {
            isInterrupted = true;
        }
    }

And for each producer thread, pass the BlockingQueue object to each, and use:

BlockingQueue<MyObject> myQueue;
// A constructor which receives the BlockingQueue object

// Create MyObjects
myQueue.offer(myObject);   // Will add to the queue

There is the concept of a queue capacity. If the producers add too quickly queue may reach capacity. An offer can fail in this case. See the javadoc LinkedBlockingQueue for full details

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.