I know that typically for producer/consumer pairs like this, a blocking queue should be used. What I want here is only to understand better memory consistency in Java, interaction between concurrent data structures and locks, and also what is exactly the imprecision when determining the size of ConcurrentLinkedQueue
.
The question is, does the algorithm below assure, that anything produced is consumed, as it would in the case of a plain non-thread safe queue? Note: I ran it several times and it always was the case.
import java.util.concurrent.ConcurrentLinkedQueue;
public class Produce extends Thread {
@Override
public void run() {
synchronized(Main.queue) {
Main.queue.add(1);
Main.queue.notifyAll();
}
}
}
public class Consume extends Thread {
@Override
public void run() {
synchronized(Main.queue) {
while(true) {
while(!Main.queue.isEmpty()) {
Main.queue.poll();
System.out.println("consumed");
}
System.out.println("empty");
try {
Main.queue.wait();
} catch(InterruptedException e) {
}
}
}
}
}
public class Main {
public static final ConcurrentLinkedQueue<Integer> queue =
new ConcurrentLinkedQueue();
public static void main(String[] args) {
(new Consume()).start();
(new Produce()).start();
}
}