ReentrantLock Example Java Concurrency

ReentrantLock Example Java Concurrency

ReentrantLock in Java is added on java.util.concurrent package in Java 1.5 along with other concurrent utilities like CountDownLatch, Executors. ReentrantLock is one of the most useful addition in Java concurrency package and several of concurrent collection classes from java.util.concurrent package is written using ReentrantLock, including ConcurrentHashMap.

ReentrantLock

In the below example, we will start two thread and inside the run method we have used lock. So only one thread can execute the code block after acquiring the lock. If you see the output first thread will start and acquired the lock and next thread failed to acquire the lock.

 

OutPut:
Inside run
failed to lock
finished run

In this example we will use lock.tryLock(20000, TimeUnit.SECONDS) , so next thread will wait for 20000 seconds to acquire the lock and finally it will acquire lock.

 

OutPut:
Inside run
finished run
Inside run
finished run

Gopal Das
Follow me

Gopal Das

Founder at GopalDas.Org
He is a technology evangelist, Salesforce trainer, blogger, and working as a Salesforce Technical Lead. After working in Java based project implementation, he jumped to the Salesforce system on a whim and never looked back. He fell in love with Salesforce’s flexibility, scalability, and power. He expanded his knowledge of the platform and became a Certified App Builder, Administrator, Platform Developer I, SalesCloud Consultant while leading the Salesforce implementation and technology needs. He has worked in a wide variety of applications/services like desktop, web and mobile applications.
Gopal Das
Follow me

1 Comment

  1. I think the article is very helpful for us,it has solved our problem,thanks!

Leave a Reply

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