Coding the Thread Deadlock


You want a deadlock right?

I wanted to make sure that I understand this correctly. Thread deadlocks are one of the issues that Core Java Developers usually faced especially if developing a high availability/performance application. They need to ensure that threads are created in an efficient manner.

I’d like to disclaim that I’m an expert on the subject matter, but I do understand why it can happen, how to identify and how can it be resolved.

Take a look at an threadlock example below:

package com.areyes.datastruct;

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 class DeadLock {
	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();
	}
}

“What is deadlock?” answer is simple, when two or more threads waiting for each other to release lock and get stuck for infinite time , situation is called deadlock . it will only happen in case of multitasking.

“How do you detect deadlock in Java?” – easy as checking and testing your code. You can also check your systems thread dump and see from there if it’s in a deadlock.

Hope this helps!