I'm trying to remove elements manually from ArrayBlockingQueue
by using the removeIf()
method, using threads.
And then have another thread trying to put an element into the ArrayBlockingQueue
.
It doesn't work, which is weird because I thought that put()
tries and tries until there's space and puts an element in successfully or is my understanding of it wrong?
What's the problem and what should I do to work around this problem?
Here's my code
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.CyclicBarrier;
class HelloWorld {
static ArrayBlockingQueue<Integer> q = new ArrayBlockingQueue(2);
static CyclicBarrier cb = new CyclicBarrier(2);
public static void main(String[] args) {
try {
Thread t1 = new Thread(() -> {
try {
q.put(2);
} catch (Exception e) {
e.printStackTrace();
}
});
Thread t2 = new Thread(() -> {
try {
q.put(2);
} catch (Exception e) {
e.printStackTrace();
}
});
Thread t3 = new Thread(() -> {
try {
q.put(1);
} catch (Exception e) {
e.printStackTrace();
}
});
t1.start();
t2.start();
t3.start();
t1.join();
t2.join();
System.out.println(q.size());
q.removeIf(ii -> ii == 2);
System.out.println(q.size());
t3.join();
System.out.println(q.size());
} catch (Exception e) {
e.printStackTrace();
}
}
}
The first output was 2, second was 0 after the removeIf() method and the third output never arrived, I think its because the put() method was never triggered. I expected the third output to be 1 as I thought the put() method will be triggered as space was vacated using removeIf(), but the third output never came no matter how long I waited