O'Reilly logo

Java™ How to Program, Seventh Edition by P. J. Deitel - Deitel & Associates, Inc., H. M. Deitel - Deitel & Associates, Inc.

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

23.8. 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. 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 it does not solve the state-dependence ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required