Comparing Thread Synchronization Mechanisms in Java
Monitor, Lock and Semaphore
Running multiple concurrent threads requires special attention when they access (perform read and write operations) the same memory block. The piece of code where this memory access happens is called a critical section, and thread access should be synchronized in order to avoid a race condition. In Java, synchronizing the access to critical sections can be done using different mechanisms: Monitor, Lock and Semaphore.
In this article, I will give a thorough comparison between these mechanisms, while trying to synchronize the well-known Producer-Consumer problem. The following code shows the basic Buffer data structure implementation. We will try to synchronize the access to both methods addItem
and getItem
, invoked from different concurrent threads.
In order to simulate the scenario, I have created two Thread
classes, namely Producer
and Consumer
, each of which would produce and consume 10 items respectively. The main application code creates a single instance of Buffer
and starts multiple threads of…