I see this example frequently and thought I'd give it a shot but I've got something unexpected happening with my Queue. I have multiple threads utilizing my producer class but the output doesn't show that it is being written to by each thread.
protected Queue<ProductMessage> prodQueue = new ConcurrentLinkedQueue<>();
@Override
public void run() {
while (true) {
prodQueue.add(new ProductMessage(MP3Util.getRandomProduct(), new Date(), MP3Util.regionLookup(MP3Util.getState())));
System.out.println(Thread.currentThread().getName() + "Queue " + prodQueue.size());
try {
Thread.sleep(2000);
} catch (InterruptedException ex) {
Logger.getLogger(ProductProducer.class.getName()).log(Level.SEVERE, null, ex);
}
}
Thread p1 = new Thread(new ProductProducer());
Thread p2 = new Thread(new ProductProducer());
p1.start();
p2.start();
The output shows:
Thread-1Queue 3
Thread-3Queue 3
Thread-1Queue 4
Thread-3Queue 4
Thread-3Queue 5
Thread-1Queue 5
Ideas? I'm pretty sure the ConcurrentLinkedQueue is "thread safe" per the API so it has to be something I'm doing.