This article explains the difference between Thread DeadLock and LiveLock with examples.
DeadLock
DeadLock occurs when two threads are blocked for each other and each one is waiting for the other to release it’s lock.
For example,
Let’s consider that we have two resources A and B and two threads Thread1 and Thread2.
Now, Thread1 acquires lock on Resource A and waits for Resource B. At the same time, Thread2 acquires lock on Resource B and waits for Resource A.
But Thread1 won’t release its lock on A, until its able to access B and similarly, Thread2 won’t release lock on B until it gets access to A. So, they just keep waiting for each other in a deadlock state.
Here is an example illustrating the deadlock scenario :
public class DeadLockSimul{ private static String ResourceA = "ResourceA"; private static String ResourceB = "ResourceB"; public void doSomething(){ synchronized(ResourceA){//may deadlock here synchronized(ResourceB){ // do something } } } public void doSomethingElse(){ synchronized(ResourceB){//may deadlock here synchronized(ResourceA){ // do something } } } }
LiveLock
LiveLock is similar to DeadLock, but the threads aren’t dead.
They are still working, but are not able to make any progress.
For example,
Lets consider that we have two resources A and B and two threads Thread1 and Thread2.
Now, Thread1 acquires lock on Resource A and fails to get lock on Resource B as Thread2 already locked it.
At the same time, Thread2 acquires lock on Resource B and waits for Resource A.
Now, Thread1 unblocks ResourceA to give Thread2 chance to get it, waits for some time and then tries to get lock on ResourceA & ResourceB again. Thread2 does the same and unlocks ResourceB for Thread1 to get a chance, waits for sometime and then comes back to get lock on ResourceB and ResourceA again. They keep doing the same thing again and again.
This scenario is a LiveLock as they threads aren’t deadlocked, but are not able to make any progress.
© 2018, https:. All rights reserved. On republishing this post, you must provide link to original post