If two threads are waiting for each other forever such type of infinite waiting is called deadlock in java. Synchronized keyword is the only reason for deadlock situation hence while using synchronized keyword we have to take special care. There is no resolution technique for deadlock, but several prevention techniques are available.
Implementation: Deadlock occurs
Here the cursor is showing forever because the threads enter into the deadlock situation. In the above program if we removed at least one synchronized keyword then the program won’t enter into the deadlock situation. Hence, synchronized keyword is one of the major reason for deadlock situation. Due to this while using synchronized keyword we have to take special care.
We can avoid Deadlock situation in the following ways:
- Using Thread.join() Method: We can get a deadlock if two threads are waiting for each other to finish indefinitely using thread join. Then our thread has to wait for another thread to finish, it is always best to use Thread.join() method with the maximum time you want to wait for the thread to finish.
- Use Lock Ordering: We have to always assign a numeric value to each lock and before acquiring the lock with a higher numeric value we have to acquire the locks with a lower numeric value.
- Avoiding unnecessary Locks: We should use locks only for those members on which it is required, unnecessary use of locks leads to a deadlock situation. And it is recommended to use a lock-free data structure and If it is possible to keep your code free from locks. For example, instead of using synchronized ArrayList use the ConcurrentLinkedQueue.
Example 2: Deadlock is prevented
Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.