Let us consider an example program that deadlocks, and then see how we could have avoided that. Below example is an example for a lock ordering deadlock.
The DeadLockExample class has two objects lockObject1 and lockObject2, which we will use as locks for synchronizing.
We will have two Runnables, which we will use for creating two threads: Runnable1 synchronizes on lockObject1 and try to get lockObject2, and Runnable2 synchronizes on lockObject2 and try to get lockObject1.
Java concurrency package give you the ability to use explicit locks. With explicit locks, you can see if a lock is available and acquire only if it is available. This way you can avoid deadlocks. We already wrote a deadlock simulation program without using explicit locks and now we will write the same program using explicit locks. This is just a rewrite and hence will also deadlock like hte older one.
Lock ordering deadlock is caused when using different order of acquiring locks when locking on multiple objects. The solution is also simple: either acquire only one lock at a time or when acquiring multiple locks, acquire them in same order, whenever feasible.
According to the book Java Concurrency in Practice, there are different types of deadlocks such as Lock ordering deadlocks, Open call deadlocks and Resource deadlocks. All the examples in this note are inspired from the examples given in the book Java Concurrency in Practice.
Lock ordering deadlock is caused when using different order of acquiring locks when locking on multiple objects.
This is a personal technical blog where we share our understanding on various concepts and is neither an official page or documentation for the products described here, nor the official views of the companies we work with.
Keywords used in this website are trademarks of their respective owners. This website is not affiliated with Oracle™ and/or any of the JEE frameworks like Spring™, Struts™, Hibernate™ and JSF™.
All contents and materials are provided freely without any warranty or liability and nothing within the site should be considered as professional advice. In any doubt, please ask, and we will try to help you based on our knowledge. Please let us know if you feel anything is not right here (including any copyright violation) and we will act upon it as fast as we can.