Overview of livelock

In a deadlock, the two processes wait for each other, but in a livelock, they actively try to solve the problem on their own. Livelock happens when a set of processes constantly try to resolve an issue by backtracking, reverting, retrying, or rolling back. The process attempts to change its state so that at least one of the processes can succeed and the system can proceed.

Example of a livelock

A livelock is much like when two people meet face to face in a corridor and both move to the same side to let the other pass. Let’s take a more technical example to understand more clearly. Assume that there are two processes, and both of them require two resources to complete the block of transactions.

Process A acquires the lock on resource x, and similarly, process B acquires the lock on resource y. But process A requires a lock on resource y as well to complete its block of transactions. As a result, instead of waiting for resources (resource y, in this case), process A will release its lock from resource x. Process B would do the same thing as well. When it proceeds, process B will first acquire the lock on resource y, but it needs the lock on resource x as well, which is currently held by process A.

Both the processes will try again, and the same thing will happen again and again. None of the processes will proceed, and the system will get stuck indefinitely.

Difference between deadlock and livelock

In a deadlock situation, if a process doesn’t have all the required resources, it will wait indefinitely for the other processes to release the lock. As a result, none of the processes will proceed, and the system will throw a deadlock error. In livelock, the processes aren’t waiting for each other. They are constantly working, hoping that one of them will eventually succeed and proceed further, but actually, they never succeed.

Livelock in Golang

Let’s look at a practical example in Golang to understand it better.

Get hands-on with 1200+ tech skills courses.