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
synchronized methods. This requires that a thread obtain the monitor lock on the
Buffer object before attempting to access the buffer data, but ...