JavaRush /Courses /C# SELF /Mutual locks: Deadlocks

Mutual locks: Deadlocks

C# SELF
Level 57, Lesson 1
Available

1. Deadlock example in C#

Deadlock is a situation where each thread in a group holds a resource and waits for another resource held by another thread in the same group — and nobody ever gets what they need.

Let's see it in practice. Suppose we have two lock objects and two threads. Each thread locks one object and then tries to acquire the second.

using System;
using System.Threading;

class Program
{
    static readonly object lockerA = new object();
    static readonly object lockerB = new object();

    static void Main()
    {
        Thread thread1 = new Thread(Thread1Work);
        Thread thread2 = new Thread(Thread2Work);

        thread1.Start();
        thread2.Start();

        thread1.Join();
        thread2.Join();

        Console.WriteLine("Both threads finished (if no Deadlock happened)");
    }

    static void Thread1Work()
    {
        lock (lockerA)
        {
            Console.WriteLine("Thread 1: acquired lockerA");
            Thread.Sleep(100); // Give the second thread a chance to acquire lockerB

            lock (lockerB)
            {
                Console.WriteLine("Thread 1: acquired lockerB");
            }
        }
    }

    static void Thread2Work()
    {
        lock (lockerB)
        {
            Console.WriteLine("Thread 2: acquired lockerB");
            Thread.Sleep(100); // Give the first thread a chance to acquire lockerA

            lock (lockerA)
            {
                Console.WriteLine("Thread 2: acquired lockerA");
            }
        }
    }
}

Run this code a few times — and you'll almost certainly hit the app "hanging". Deadlock happened! Each thread grabbed its lock and now waits for the other to release the other lock.

Deadlock visualization

Here's a diagram of how it looks:

sequenceDiagram
    participant Thread 1
    participant Thread 2
    participant lockerA
    participant lockerB

    Thread 1->>lockerA: acquire lockerA
    Thread 2->>lockerB: acquire lockerB
    Thread 1->>lockerB: waiting for lockerB to be released
    Thread 2->>lockerA: waiting for lockerA to be released

Result: Thread 1 holds lockerA and waits for lockerB, Thread 2 holds lockerB and waits for lockerA. Nobody yields — the program is stuck.

2. How to detect Deadlock?

Why does this happen?

To understand the reason, let's look at a few ingredients:

  • Multiple locking: When a thread acquires several locks at once.
  • Incorrect lock order: If threads lock resources in different orders, a deadlock can occur.
  • Possibility to wait: A thread waits for a resource that's held by another thread.
  • No forced takeover: One thread can't "steal" a lock from another in C# — it can only wait.

The classic trap: if you have N threads and N resources, and threads lock them in different orders, you're on the verge of a deadlock.

Typical signs of Deadlock

From the outside, deadlock usually looks like a normal program "hang". Threads are alive but waiting for access to resources, endlessly waiting for each other.

Typical signs:

  • The program unexpectedly stopped responding (sometimes only under certain load).
  • The debugger shows threads stuck on lock, Monitor.Enter, WaitOne, EnterReadLock or similar sync operations.
  • System tools (like Task Manager or Rider/Visual Studio tools) show 0% CPU usage — "everything is stalled".
  • Logs show no errors but also no activity.

If you use JetBrains Rider or Visual Studio, inspect the debugger to see where your threads are stuck (Stack Trace). If you see multiple threads waiting on lock/Mutex.WaitOne for each other — congrats (or condolences): that's a deadlock!

Classic deadlock scenarios

Inconsistent lock ordering. Like in our example above: Thread 1 locks lockerA then lockerB; Thread 2 does the opposite. Trap set.

Nested locks. When inside one lock block you do another lock on a different object.

Overlapping resources across methods. Especially hard to track when locks are scattered across different methods/classes and appear in different combinations. Scenarios get more complex when there are more than two locks.

3. Preventing Deadlock

Good news: you can protect against deadlock!
Bad news: you need to be careful when designing multithreaded code.

Here are some practical recommendations (remember them — they'll help in interviews!):

Always acquire locks in the same order

If you have several objects that can be locked together — define a global order (e.g., by name or index) and always follow it.

Example — acquiring locks safely

static void SafeLock(object objA, object objB)
{
    // Compare hashes — so threads always lock objects in the same order
    object first = objA.GetHashCode() < objB.GetHashCode() ? objA : objB;
    object second = objA.GetHashCode() < objB.GetHashCode() ? objB : objA;

    lock (first)
    {
        lock (second)
        {
            // critical section
        }
    }
}

Here — both threads will enter lock(objA) first, then lock(objB), if objA is "less" than objB.

Use timeouts

If a thread can't get a lock within a reasonable time — let it throw or exit gracefully. Monitor.TryEnter is suitable.

Example with Monitor.TryEnter

bool lockTakenA = false;
bool lockTakenB = false;

try
{
    Monitor.TryEnter(lockerA, 500, ref lockTakenA);
    if (!lockTakenA)
    {
        // Failed to get lock in 500 ms — give up to avoid deadlock
        return;
    }

    Monitor.TryEnter(lockerB, 500, ref lockTakenB);
    if (!lockTakenB)
    {
        return;
    }

    // Critical section...

}
finally
{
    if (lockTakenB)
        Monitor.Exit(lockerB);
    if (lockTakenA)
        Monitor.Exit(lockerA);
}

If you can't get the lock — don't hang!

Minimize locked regions

Keep only the absolutely necessary code inside critical sections.

Don't mix different synchronization mechanisms

If you use lock, Mutex, Semaphore, ReaderWriterLockSlim at the same time — it's easier to get confused and cause a deadlock.

4. Deadlock with Mutex, Semaphore and ReaderWriterLockSlim

Mutual locks can occur not only with classic lock or Monitor, but also with other synchronization primitives.

Deadlock with Mutex

static Mutex mutexA = new Mutex();
static Mutex mutexB = new Mutex();

void Work1()
{
    mutexA.WaitOne();
    Thread.Sleep(100);
    mutexB.WaitOne();

    // Critical section

    mutexB.ReleaseMutex();
    mutexA.ReleaseMutex();
}

If a second thread grabs them in the opposite order — you'll get a deadlock.

Deadlock with ReaderWriterLockSlim

ReaderWriterLockSlim, despite being flexible, doesn't protect you from deadlocks if a thread already holds one type of lock and tries to get another.

For example, if a thread holds a read-lock (EnterReadLock) and tries to enter a write-lock (EnterWriteLock) — deadlock is guaranteed, because a write-lock can't be obtained while read-locks are held.

5. How to avoid Deadlock in real apps

Let's see how this could look in our demo app. Suppose we develop an online shop simulator where these run concurrently:

  • Threads updating stock counts (writers)
  • Threads checking product availability (readers)
  • An admin (special thread) that both reads and writes

Bad:

lock (stockLock)
{
    // update stock
    lock (userLock)
    {
        // something with users
    }
}
// ... and somewhere else the opposite!
lock (userLock)
{
    lock (stockLock) { }
}

Good:

Agree — always try to lock stockLock first, then userLock in all threads.

6. How not to get Deadlock at work and in interviews

In real projects:

  • When designing — draw diagrams of threads and locks (paper/whiteboard is fine).
  • Share the lock-order convention with the whole team.
  • Use static analysis tools (Rider/Visual Studio, ReSharper) — they can find potential deadlocks.
  • Read articles on Microsoft Docs about Deadlock.

In interviews:

  • Show that you understand the problem and its classic symptoms.
  • Mention main protection techniques: consistent order, timeouts (TryEnter), minimal critical sections.
  • Give an example with TryEnter and explain why it's important to release all acquired resources in finally.

7. Common mistakes and surprising Deadlocks

Mistake #1: non-obvious locks inside third-party libraries.
Classic case — logging inside a critical section. A thread gets stuck and you don't even realize it's caused by someone else's code.

Mistake #2: re-locking the same resource.
This is a reentrant deadlock: a thread tries to enter a lock it already holds, but the mechanism doesn't support reentry.

Mistake #3: using async methods inside critical sections.
Especially dangerous with await: control can be yielded at the worst moment and block the whole system.

2
Task
C# SELF, level 57, lesson 1
Locked
Deadlock Demonstration
Deadlock Demonstration
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION