Sobes.tech
Senior

What is a livelock between two threads and how to avoid it?

sobes.tech AI

Answer from AI

Livelock is a situation where two or more threads constantly react to each other, trying to avoid deadlock, but are unable to make progress, constantly changing state.

Unlike deadlock, where threads wait for each other, in livelock, threads are active but do not do useful work.

Example: two threads try to acquire two resources, release them, and try again to avoid deadlock, but keep interfering with each other.

How to avoid livelock:

  • Use stricter resource acquisition protocols, such as a fixed acquisition order.
  • Introduce random delays (backoff) before retrying to acquire resources.
  • Use high-level synchronization constructs from java.util.concurrent that minimize the risk of livelock.

Example with backoff:

while (true) {
    if (tryLock(resource1)) {
        if (tryLock(resource2)) {
            // Work with resources
            unlock(resource2);
            unlock(resource1);
            break;
        } else {
            unlock(resource1);
            Thread.sleep(randomBackoff());
        }
    } else {
        Thread.sleep(randomBackoff());
    }
}