Using a blocking thread-safe queue for communicating with producers and consumers

The producer/consumer problem is a classical problem in concurrent programming. You have one or more producers of data that store this data in a buffer. You also have one or more consumers of data that take the data from the same buffer. Both producers and consumers share the same buffer, so you have to control access to it to avoid data inconsistency problems. When the buffer is empty, the consumers wait until the buffer has elements. If the buffer is full, the producers wait until the buffer has empty space.

This problem has been implemented using almost all the techniques and synchronization mechanisms developed in Java and in other languages (refer to the ...

Get Java 9 Concurrency Cookbook - Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.