26.7 Producer/Consumer Relationship with Synchronization

The previous example showed how multiple threads can share a single-element buffer in a thread-safe manner by using the ArrayBlockingQueue class that encapsulates the synchronization necessary to protect the shared data. For educational purposes, we now explain how you can implement a shared buffer yourself using the synchronized keyword and methods of class Object. Using an ArrayBlockingQueue will result in more-maintainable and better-performing code.

The first step in synchronizing access to the buffer is to implement methods get and set as synchronized methods. This requires that a thread obtain the monitor lock on the Buffer object before attempting to access the buffer data, but ...

Get Java How to Program (early objects), 9/e 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.