Thread in monitor (BLOCKED) state due to deadlock example and jvisualvm analysis

public class ThreadBlockedTest {

	static class Thread0 extends Thread {
		static synchronized void synchR() {
			System.out.println(Thread.currentThread().getName() + " entered sync r");
			ThreadBlockedTest.sleep(50);
			ThreadBlockedTest.synchM();
			System.out.println(Thread.currentThread().getName() + " left sync r");
		}

		@Override
		public void run() {
			System.out.println(Thread.currentThread().getName() + " started");
			synchR();
			System.out.println(Thread.currentThread().getName() + " stopped");
		}
	}; 
	
	public static void main(String[] args) throws InterruptedException {
		System.out.println(Thread.currentThread().getName() + " started");
		new Thread0().start();
		synchM();
		System.out.println(Thread.currentThread().getName() + " stopped");
	}
	
	static synchronized void synchM() {
		System.out.println(Thread.currentThread().getName() + " entered sync m");
		sleep(10);
		Thread0.synchR();
		System.out.println(Thread.currentThread().getName() + " left sync m");
	}

	private static void sleep(int i) {
		try {
			Thread.sleep(i);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}
}

Output:
main started
main entered sync m
Thread-0 started
Thread-0 entered sync r

Explanation:
two threads, both entering separate synchronized method holding a separate lock. After some time one thread while being in synchronized block tries to access another synchronized method associated to the different lock that is being already taken by another thread. While waiting for the lock, the another thread finishes sleeping and wants to access the other synchronized block without releasing the lock it has been owning. 

ThreadBlockedTest

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