Java — Ways to avoid deadlock situation in your code
Deadlock — this is the term we use in threads many times.
What is deadlock?
Deadlock is the situation where two threads waiting indefinitely on each other to release a lock on a part of code or complete block

How does deadlock situation occurs?
OK. In the definition, we told that deadlock situation waits for the lock to be released and lock is caused by making a block synchronized. From this we can infer that deadlock occurs due to synchronized blocks.
There is one more situation, thread.join() , this method waits for the other thread indefinitely.
Ways to avoid the deadlock situation
- Using the synchronized keyword very limited and restrict usage only if it is required
- Using thread.join() with a timer that the thread should wait for other thread to finish.
- Using lock free code by avoiding the locks. For example, instead of using Synchronized map we can always use concurrent map or using Concurrent Linked Queue instead of Synchronized ArrayList.
- Using lock ordering by giving a number to each lock so that program should decide which order the locks to be acquired
- Avoid nested locks where threads so that we can avoid locks to be allocated to multiple threads
Hope this article gives you basic overview of deadlock and how to overcome it. It all depends on how well the code is structured. Good coding strategies are always good to avoid unknown issues coming up.
Happy Coding!!!