TIL-10: What is a Deadlock?

Recep İnanç
2 min readDec 6, 2019

--

Photo by Yuri Catalano from Pexels

“Today I learned that a deadlock occurs when you cannot manage your locks well.”

We use locks to manage access to shared resources. In multi-threaded environments ensuring resources’ integrity and consistency are crucial. However, inattentive use of locks may cause deadlocks.

Deadlock

A deadlock occurs when the waiting process is still holding on to another resource that the first needs before it can finish.

Let’s look at an example to see how a deadlock occurs:

Process A and B Locks X and Y to use, but creates a deadlock.
  • Process A wants to access resource X and locks it so that it is ensured it is not being altered.
  • At the same time, Process B wants to access resource Y and does the same as A and locks Y exclusively for itself.
  • As the next step Process A needs the value of Y so that it can continue its operation, but it cannot get it because it is locked by Process B.
  • At the same time, Process B needs the value of X to continue its operation, but it cannot get it either because X is locked by Process A.

So in the above example, Process A waits for Y and Process B waits for X at the same time thus creating a never-ending wait loop, which is called a Deadlock.

Deadlock Example in Java

Cheers!

--

--

Recep İnanç
Recep İnanç

Written by Recep İnanç

Software Developer @Amazon. You can find me at recepinanc.com. My opinions are my own.

No responses yet