What is deadlock in java?
A lock occurs when multiple processes try to access the same resource at the same time. A deadlock occurs when the waiting process is still holding on to another resource that the first needs before it can finish. A Java multithreaded program may suffer from the deadlock condition because the synchronized keyword causes the executing thread to block while waiting for the lock, or monitor , associated with the specified object.
Resource1 and resource2 are used by Thread1 and Thread2
- Thread1 starts to use Resource1
- Thread1 and Thread2 try to start using resource2
- Thread2 'wins' and gets resource2 first
- now Thread2 needs to use Resource1
- Resource1 is already locked by Thread1, which is waiting for Thread2
The above situation create deadlock because :
- Thread 1 locks Resource1, waits for resource2
- Thread 2 locks resource2, waits for Resource1
The best way to avoid deadlocks are:
- avoid having locks (if possible)
- avoid having more than one lock
- always take the locks in the same order
If two threads which attempt to execute method transfer(a, b) and transfer(b, a) at the same time, then a deadlock is going to occur because they try to acquire the resources in reverse order.