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 O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.