O'Reilly logo

Java RMI by William Grosso

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Deadlock

My boss came into my office a couple of weeks ago. “The database metrics aren’t being recorded again. I think the storage thread is running into a deadlock.”

“Why?” I asked.

“Server problems are always deadlocks,” he replied.

Technically, he was, of course, incorrect. Servers experience many other types of problems. But there was, nonetheless, a kernel of truth to what he said. Deadlock, a situation in which two (or more) threads block each other and force each other to wait forever, is far and away the single most common serious mistake made in writing multithreaded code.

The simplest deadlock scenario involves two threads and two locks. The first thread already has the first lock and is trying to acquire the second lock. The second thread has the second lock and is trying to acquire the first lock.

For example, this could be caused by two methods with the following structure:

public synchronized void method1(...) {
	otherObject.method2(  );
}

public synchronized void method2(...) {
	otherObject.method1(  );
}

If there are two methods like this in your code, the following situation can arise:

  1. The first thread enters method1 on object1. As part of doing so, it grabs the lock associated with object1. It then prepares to call method2 on another object (which we’ll refer to as object2).

  2. At which point, the thread scheduler deactivates the first thread and activates the second thread. The second thread calls method2 on object2, and as part of doing so, grabs the lock associated ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required