There was a thread on StackOverflow recently about an interview question where the candidate was asked to write a program that will always deadlock.

Eric Lippert’s example is shorter than mine, but I think my answer (which I’m posting here because the question is labeled as a Java question) is probably easier to understand. It uses an AutoResetEvent to block the main thread in a synchronized codeblock, while another thread is waiting to obtain the lock.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
class Program {
 
    static object a = new object();
    static AutoResetEvent are = new AutoResetEvent(false);
 
    static void lock_a() {
 
        // deadlock here.
        lock (a) {
            are.Set();
        }
 
    }
 
    static void Main(string[] args) {
 
        lock (a) {
 
            Thread thread = new Thread(new ThreadStart(lock_a));
            thread.Start();
            are.WaitOne();
            // deadlock here.
 
        }
 
    }
 
}

The call to Set() will never be reached, but I put it there because otherwise, the deadlock doesn’t depend on the synchronized codeblocks. In other words, it might as well just be this:

class Program {
    static void Main() {
        AutoResetEvent are = new AutoResetEvent(false);
        are.WaitOne();
    }
}
Categories: .NETC#

Leave a Reply