How to detect Java Deadlocks?

Symptoms: When system / process is hanging we need to suspect that resources are waiting for some other resources.

Simulation: The following code simulate dead lock. Run the code.

http://dileepg2k.blogspot.com/2011/02/simulate-java-thread-deadlock.html

public class Deadlock {
	public static void main(String[] args) {
		// resource objects
		final Object resource1 = "resource 1";
		final Object resource2 = "resource 2";
		// Here's the first thread. It tries to lock resource1 then resource2
		Thread t1 = new Thread() {
			public void run() {
				// Lock resource 1
				synchronized (resource1) {
					System.out.println("Thread 1: locked resource 1");
					try {
						Thread.sleep(50);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
					synchronized (resource2) {
						System.out.println("Thread 1: locked resource 2");

					}
				}
			}
		};

		// Here's the second thread. It tries to lock resource2 then resource1.
		// Reverse order of Thread1
		Thread t2 = new Thread() {
			public void run() {
				// This thread locks resource 2 right away
				synchronized (resource2) {
					System.out.println("Thread 2: locked resource 2");
					try {
						Thread.sleep(50);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
					synchronized (resource1) {
						System.out.println("Thread 2: locked resource 1");

					}
				}
			}
		};

		// Start the two threads. If all goes as planned, deadlock will occur,
		// and the program will never exit.
		t1.start();
		t2.start();
	}
}

Step 2: Download and Run the visual vm. http://visualvm.java.net/

Step 3: Take the thread dump and go to the end of it.

How to Prevent deadlocks?
1. Make sure that not using singleton classes.
2. Set timeouts clearly.
3. Close / Release resources cleanly.
4. Always run the code for 48 hours with JMeter with full load to make sure that all are working fine.
…Need to write more here….
-0-

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s