编写一个肯定会陷入僵局的程序

我最近在一次采访中被问到这个问题。

我回答说,如果交错错误就会出现死锁,但是面试官坚持认为,无论交错如何都会陷入死锁的程序可以写出来。

我们能编写这样的程序吗? 你能给我举一些这样的例子吗?

34270 次浏览

Here is an Example from the documentation:

public class Deadlock {
static class Friend {
private final String name;
public Friend(String name) {
this.name = name;
}
public String getName() {
return this.name;
}
public synchronized void bow(Friend bower) {
System.out.format("%s: %s"
+ "  has bowed to me!%n",
this.name, bower.getName());
bower.bowBack(this);
}
public synchronized void bowBack(Friend bower) {
System.out.format("%s: %s"
+ " has bowed back to me!%n",
this.name, bower.getName());
}
}


public static void main(String[] args) {
final Friend alphonse =
new Friend("Alphonse");
final Friend gaston =
new Friend("Gaston");
new Thread(new Runnable() {
public void run() { alphonse.bow(gaston); }
}).start();
new Thread(new Runnable() {
public void run() { gaston.bow(alphonse); }
}).start();
}
}

A simple search gave me the following code:

public class Deadlock {
static class Friend {
private final String name;
public Friend(String name) {
this.name = name;
}
public String getName() {
return this.name;
}
public synchronized void bow(Friend bower) {
System.out.format("%s: %s"
+ "  has bowed to me!%n",
this.name, bower.getName());
bower.bowBack(this);
}
public synchronized void bowBack(Friend bower) {
System.out.format("%s: %s"
+ " has bowed back to me!%n",
this.name, bower.getName());
}
}


public static void main(String[] args) {
final Friend alphonse =
new Friend("Alphonse");
final Friend gaston =
new Friend("Gaston");
new Thread(new Runnable() {
public void run() { alphonse.bow(gaston); }
}).start();
new Thread(new Runnable() {
public void run() { gaston.bow(alphonse); }
}).start();
}
}

Source: Deadlock

Deadlock happens when threads (or whatever your platform calls its execution units) acquire resources, where each resource can only be held by one thread at a time, and holds on to those resources in a such a way that the holds cannot be preempted, and there exists some "circular" relationship between the threads such that each thread in the deadlock is waiting to acquire some resource held by another thread.

So, an easy way to avoid deadlock is to give some total ordering to resources and impose a rule that resources are only ever acquired by threads in order. Conversely, a deadlock can be intentionally created by running threads that acquire resources, but do not acquire them in order. For example:

Two threads, two locks. The first thread runs a loop that attempts to acquire the locks in a certain order, the second thread runs a loop that attempts to acquire the locks in the opposite order. Each thread releases both locks after successfully acquiring the locks.

public class HighlyLikelyDeadlock {
static class Locker implements Runnable {
private Object first, second;


Locker(Object first, Object second) {
this.first = first;
this.second = second;
}


@Override
public void run() {
while (true) {
synchronized (first) {
synchronized (second) {
System.out.println(Thread.currentThread().getName());
}
}
}
}
}


public static void main(final String... args) {
Object lock1 = new Object(), lock2 = new Object();
new Thread(new Locker(lock1, lock2), "Thread 1").start();
new Thread(new Locker(lock2, lock1), "Thread 2").start();
}
}

Now, there have been a few comments in this question that point out the difference between the likelihood and the certainty of deadlock. In some sense, the distinction is an academic issue. From a practical standpoint, I'd certainly like to see a running system that doesn't deadlock with the code I've written above :)

However, interview questions can be academic at times, and this SO question does have the word "surely" in the title, so what follows is a program that certainly deadlocks. Two Locker objects are created, each is given two locks and a CountDownLatch used to synchronize between the threads. Each Locker locks the first lock then counts down the latch once. When both threads have acquired a lock and counted down the latch, they proceed past the latch barrier and attempt to acquire a second lock, but in each case the other thread already holds the desired lock. This situation results in a certain deadlock.

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;


public class CertainDeadlock {
static class Locker implements Runnable {
private CountDownLatch latch;
private Lock first, second;


Locker(CountDownLatch latch, Lock first, Lock second) {
this.latch = latch;
this.first = first;
this.second = second;
}


@Override
public void run() {
String threadName = Thread.currentThread().getName();
try {
first.lock();
latch.countDown();
System.out.println(threadName + ": locked first lock");
latch.await();
System.out.println(threadName + ": attempting to lock second lock");
second.lock();
System.out.println(threadName + ": never reached");
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
}


public static void main(final String... args) {
CountDownLatch latch = new CountDownLatch(2);
Lock lock1 = new ReentrantLock(), lock2 = new ReentrantLock();
new Thread(new Locker(latch, lock1, lock2), "Thread 1").start();
new Thread(new Locker(latch, lock2, lock1), "Thread 2").start();
}
}

The latch here ensure that both locks are held when each thread tries to lock the other:

import java.util.concurrent.CountDownLatch;


public class Locker extends Thread {


private final CountDownLatch latch;
private final Object         obj1;
private final Object         obj2;


Locker(Object obj1, Object obj2, CountDownLatch latch) {
this.obj1 = obj1;
this.obj2 = obj2;
this.latch = latch;
}


@Override
public void run() {
synchronized (obj1) {


latch.countDown();
try {
latch.await();
} catch (InterruptedException e) {
throw new RuntimeException();
}
synchronized (obj2) {
System.out.println("Thread finished");
}
}


}


public static void main(String[] args) {
final Object obj1 = new Object();
final Object obj2 = new Object();
final CountDownLatch latch = new CountDownLatch(2);


new Locker(obj1, obj2, latch).start();
new Locker(obj2, obj1, latch).start();


}


}

Interesting to run jconsole, which will correctly show you the deadlock in the Threads tab.

It's not a simplest interview task you can get: in my project, it paralysed a team's work for a whole day. It's very easy to make your program stop, but it's very hard to get it to the state where thread dump writes something like,

Found one Java-level deadlock:
=============================
"Thread-2":
waiting to lock monitor 7f91c5802b58 (object 7fb291380, a java.lang.String),
which is held by "Thread-1"
"Thread-1":
waiting to lock monitor 7f91c6075308 (object 7fb2914a0, a java.lang.String),
which is held by "Thread-2"


Java stack information for the threads listed above:
===================================================
"Thread-2":
at uk.ac.ebi.Deadlock.run(Deadlock.java:54)
- waiting to lock <7fb291380> (a java.lang.String)
- locked <7fb2914a0> (a java.lang.String)
- locked <7f32a0760> (a uk.ac.ebi.Deadlock)
at java.lang.Thread.run(Thread.java:680)
"Thread-1":
at uk.ac.ebi.Deadlock.run(Deadlock.java:54)
- waiting to lock <7fb2914a0> (a java.lang.String)
- locked <7fb291380> (a java.lang.String)
- locked <7f32a0580> (a uk.ac.ebi.Deadlock)
at java.lang.Thread.run(Thread.java:680)

So the goal would be to get a deadlock which JVM will consider a deadlock. Obviously, no solution like

synchronized (this) {
wait();
}

will work in that sense, even though they will indeed stop forever. Relying on a race condition is not a good idea, either, as during interview you usually want to show something provably working, not something which should work most of the time.

Now, the sleep() solution is okay in a sense it's hard to imagine a situation where it doesn't work, but not fair (we're in a fair sport, aren't we?). The solution by @artbristol (mine is the same, just different objects as monitors) is nice, but long and uses the new concurrency primitives to get the threads in the the right state, which is not that much fun:

public class Deadlock implements Runnable {
private final Object a;
private final Object b;
private final static CountDownLatch latch = new CountDownLatch(2);


public Deadlock(Object a, Object b) {
this.a = a;
this.b = b;
}


public synchronized static void main(String[] args) throws InterruptedException {
new Thread(new Deadlock("a", "b")).start();
new Thread(new Deadlock("b", "a")).start();
}


@Override
public void run() {
synchronized (a) {
latch.countDown();
try {
latch.await();
} catch (InterruptedException ignored) {
}
synchronized (b) {
}
}
}
}

I do recall that the synchronized-only solution fits 11..13 lines of code (excluding comments and imports), but have yet to recall the actual trick. Will update if I do.

Update: here's an ugly solution on synchronized:

public class Deadlock implements Runnable {
public synchronized static void main(String[] args) throws InterruptedException {
synchronized ("a") {
new Thread(new Deadlock()).start();
"a".wait();
}
synchronized ("") {
}
}


@Override
public void run() {
synchronized ("") {
synchronized ("a") {
"a".notifyAll();
}
synchronized (Deadlock.class) {
}
}
}
}

Note we replace a latch with an object monitor (using "a" as an object).

import java.util.concurrent.CountDownLatch;


public class SO8880286 {
public static class BadRunnable implements Runnable {
private CountDownLatch latch;


public BadRunnable(CountDownLatch latch) {
this.latch = latch;
}


public void run() {
System.out.println("Thread " + Thread.currentThread().getId() + " starting");
synchronized (BadRunnable.class) {
System.out.println("Thread " + Thread.currentThread().getId() + " acquired the monitor on BadRunnable.class");
latch.countDown();
while (true) {
try {
latch.await();
} catch (InterruptedException ex) {
continue;
}
break;
}
}
System.out.println("Thread " + Thread.currentThread().getId() + " released the monitor on BadRunnable.class");
System.out.println("Thread " + Thread.currentThread().getId() + " ending");
}
}


public static void main(String[] args) {
Thread[] threads = new Thread[2];
CountDownLatch latch = new CountDownLatch(threads.length);
for (int i = 0; i < threads.length; ++i) {
threads[i] = new Thread(new BadRunnable(latch));
threads[i].start();
}
}
}

The program always deadlocks because each thread is waiting at the barrier for the other threads, but in order to await the barrier, the thread must be holding the monitor on BadRunnable.class.

UPDATE: This question was the subject of my blog in January 2013. Thanks for the great question!


How can we write a program that will always go into deadlock no matter how the threads are scheduled?

Here's an example in C#. Note that the program appears to contain no locks and no shared data. It has only a single local variable and three statements, and yet it deadlocks with 100% certainty. One would be hard-pressed to come up with a simpler program that deadlocks with certainty.

Exercise to the reader #1: explain how this deadlocks. (An answer is in the comments.)

Exercise to the reader #2: demonstrate the same deadlock in Java. (An answer is here: https://stackoverflow.com/a/9286697/88656)

class MyClass
{
static MyClass()
{
// Let's run the initialization on another thread!
var thread = new System.Threading.Thread(Initialize);
thread.Start();
thread.Join();
}


static void Initialize()
{ /* TODO: Add initialization code */ }


static void Main()
{ }
}

Here's sample where one thread holding lock starts another thread which wants the same lock and then starter waits until started finishes... forever:

class OuterTask implements Runnable {
private final Object lock;


public OuterTask(Object lock) {
this.lock = lock;
}


public void run() {
System.out.println("Outer launched");
System.out.println("Obtaining lock");
synchronized (lock) {
Thread inner = new Thread(new InnerTask(lock), "inner");
inner.start();
try {
inner.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}


class InnerTask implements Runnable {
private final Object lock;


public InnerTask(Object lock) {
this.lock = lock;
}


public void run() {
System.out.println("Inner launched");
System.out.println("Obtaining lock");
synchronized (lock) {
System.out.println("Obtained");
}
}
}


class Sample {
public static void main(String[] args) throws InterruptedException {
final Object outerLock = new Object();
OuterTask outerTask = new OuterTask(outerLock);
Thread outer = new Thread(outerTask, "outer");
outer.start();
outer.join();
}
}

There's an example in Java here

http://baddotrobot.com/blog/2009/12/24/deadlock/

Where a kidnapper gets into a deadlock when he refuses to give up the victim until he gets the cash but the negotiator refuses to give up the cash until he gets the victim.

Here is a Java example by following Eric Lippert's one:

public class Lock implements Runnable {


static {
System.out.println("Getting ready to greet the world");
try {
Thread t = new Thread(new Lock());
t.start();
t.join();
} catch (InterruptedException ex) {
System.out.println("won't see me");
}
}


public static void main(String[] args) {
System.out.println("Hello World!");
}


public void run() {
Lock lock = new Lock();
}


}

Here is an example:

two threads are running , each one waiting for other to release lock

public class ThreadClass extends Thread{

String obj1,obj2;
ThreadClass(String obj1,String obj2){
this.obj1=obj1;
this.obj2=obj2;
start();
}


public void run(){
synchronized (obj1) {
System.out.println("lock on "+obj1+" acquired");


try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("waiting for "+obj2);
synchronized (obj2) {
System.out.println("lock on"+ obj2+" acquired");
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}


}




}

}

Running this would lead to deadlock:

public class SureDeadlock {

public static void main(String[] args) {
String obj1= new String("obj1");
String obj2= new String("obj2");


new ThreadClass(obj1,obj2);
new ThreadClass(obj2,obj1);




}

}

I've rewritten Yuriy Zubarev's Java version of the deadlock example posted by Eric Lippert: https://stackoverflow.com/a/9286697/2098232 to more closely resemble the C# version. If the Java's initialization block works similarily to C# static constructor and first acquires the lock we don't need another thread to also invoke the join method to get a deadlock, it only needs to invoke some static method from Lock class, like the original C# example. Resulting deadlock seems to confirm this.

public class Lock {


static {
System.out.println("Getting ready to greet the world");
try {
Thread t = new Thread(new Runnable(){


@Override
public void run() {
Lock.initialize();
}


});
t.start();
t.join();
} catch (InterruptedException ex) {
System.out.println("won't see me");
}
}


public static void main(String[] args) {
System.out.println("Hello World!");
}


public static void initialize(){
System.out.println("Initializing");
}


}

This C# version, I guess java should be pretty similar.

static void Main(string[] args)
{
var mainThread = Thread.CurrentThread;
mainThread.Join();


Console.WriteLine("Press Any key");
Console.ReadKey();
}