Reentrant Lock

The ReentrantLock class is an implementation of Lock Interface, which will lock() the execution block for the thread which calls it.
Until the locked thread calls the lock.unlock() method, the code block in between will not be available to other Threads…even when it is idle or sleeping or taking long time.
Hence the block after lock.lock() is thread safe until the calling thread calls lock.unlock().

In this example, we have created simply 4 threads parallely to act on a single Object.
We use Reentrant Lock Object to lock the code block, from other threads, making one thread executing the code block.
we could see in results, until one thread completes the block, other thread will be waiting for to enter the code block.
If we remove the lock object, we could see all threads will call the methods parallely and executing the code block at same instant change the values concurrently.

 


Here we could see until the thread release the lock, other thread cannot acquire/take the lock.
Remaining Threads are waiting for the current thread to release the lock.

Result:


If we are removing the re-entrant lock object everywhere or remove the lock.lock and unlock methods,
we could see all the objects parallely executing on the single object not waiting for each other, however not thread safe.
In the above example, we could see until the thread release the lock, other thread cannot take the lock.
However in the below result, we could see all the threads are executing the blocks independently.
Example Result if we comment out lock.lock() and lock.unlock() methods in above example.


You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *