| |
Struts Tutorials:
Struts2 Tag CheckBoxList , Checkbox, Iterator, IF
Struts2 Tag Library Example
Struts2 Tiles Example
Struts2 Tiles I18N Example
Struts2 Questions
Struts Tiles I18N Example
Struts Eclipse MVC
Struts2 Tags
Struts2 Example and Tutorial
Struts MVC
Struts2 Validation
Hibernate Tutorials:
Hibernate Case Study
Class Hierarchy Persist Example
Using Hibernate Interceptor
Hibernate Questions with Answer
Hibernate Many-to-Many Mapping Example
Hibernate one-to-many Mapping Example
Hibernate and ORM tools
Spring Hibernate Example
Hibernate SessionFactory Example
Hibernate Mapping Class Hierarchy
Hibernate Questions
Hibernate SessionFactory Questions
Spring Hibernate Example:
Spring Hibernate Case Study
Written By : Amit
Title :
Java IO Basics
Description :
Understanding Input Output Streams More...
|
Written By : Sameer
Title :
Java Comparator and compareTo
Description :
Question More...
|
Written By : Sameer
Title :
Apache ServiceMix
Description :
SOA and ESB More...
|
Written By : kkk_f17
Title :
Question on String in Java
Description :
How to improve performance More...
|
Written By : guddu
Title :
Tomcat and LDAP
Description :
Integration for Enterprise SSO More...
|
Written By : Amit
Title :
SSO
Description :
Single Sign On More...
|
Written By : Amit
Title :
Swing or AWT
Description :
Why to choose either More...
|
Written By : Girish
Title :
ACL Tag Library
Description :
Using Java in Web Application More...
|
| Tags/Keywords : Example--Java-Thread-Deadlock - Thread-Deadlock-Java - Your-Questions-on-Java Example Author : Amit Date (Year/Month/Date): 2009-05-29
Thread Deadlock example using Java Technology | |
Please be informed that NONE of the design/code from this
page is claiming to be some sort of best practices and we DO NOT expect
any of our visitor/reader of this page to assume this as some sort of
best practice for any context and should not be using this
as it is without appropriate evaluation to their, so to say,
specific programming context.
This page intends only to provide bit and piece of known ways for
doing some sort of example and may not be fit for any other purpose.
How Deadlock may occur while using Java Thread API? a simple to understand
example explained.
We are going to discuss two scenarios, one, where multi threading example
runs perfectly, and the second one, where Deadlock occurs after running code
for sometime.
In this example, we have two threads, accessing two Java POJO beans,
each bean is accessing the other bean to print the required message,
And methods in both Java beans are made as synchronized.
In this example we shall see that, just by making methods from two beans
accessing one another's synchronized methods, is not going to produce
deadlock, but when these two beans are defined as singleton or multiple
threads are accessing same instances or object references of beans with
multiple synchronized methods accessing one another, then only deadlock
may happen. The reason is that synchronization locks an instance
of a Java Object, not on all occurrence of the same Java Objects if
instantiated multiple times (in case of non singleton approach).
If WorkA and WorkB are defined as normal class (not singleton), then
two threads "Thread 1" and "Thread 2" accessing WorkA and WorkB Java Object
respectively and for Thread1 both WorkA and WorkB objects references are
different from those accessed by Thread2, so here in this case no deadlock
occurs, as each thread completes its task by using two separate instances of
WorkA and WorkB.
But please have a look at the following image:
Diagram: 1
Here both threads 1 and 2 executes by obtaining lock or monitor of
one Java Object (WorkA and WorkB respectively), then deadlock can occur, at
the execution of point number 3 and 4.
In this second scenario WorkA and WorkB are defined as Singleton (one instance
per JVM), Two threads work on only two instance, one of WorkA and another that
of WorkB.
Even if WorkA and WorkB are not Singleton, then also if same instance of WorkA
and WorkB are shared by both the Threads as shown in Diagram 2, then also
Thread Deadlock may happen, as depicted in diagram below:
Diagram: 2
So comming back to code, following are the required classes as discussed above:
Scenario 1: where both WorkA and WorkB are singleton and two threads Thread1 and
Thread2 are accessing objects of these two Singleton classes:
WorkA.java
package demo;
public class WorkA {
private WorkB workB;
private final static WorkA workA = new WorkA();
private WorkA(){
}
public static WorkA getInstance() {
return workA;
}
public void setWorkB(WorkB workB) {
this.workB = workB;
}
public synchronized void method1() {
workB.method2();
}
public synchronized void method4() {
System.out.println("Inside WorkA.method4....");
}
}
WorkB.java
package demo;
public class WorkB {
private WorkA workA;
private final static WorkB workB = new WorkB();
private WorkB() {
}
public static WorkB getInstance() {
return workB;
}
public void setWorkA(WorkA workA) {
this.workA = workA;
}
public synchronized void method2() {
System.out.println("Inside WorkB.method2....");
}
public synchronized void method3() {
workA.method4();
}
}
TestClient.java - Thread1 and Thread2 as Runnable
package demo;
public class TestClient {
public TestClient() {
WorkA workA = WorkA.getInstance();
WorkB workB = WorkB.getInstance();
workA.setWorkB(workB);
workB.setWorkA(workA);
Thread thread1 = new Thread(new Thread1(workA,workB));
Thread thread2 = new Thread(new Thread2(workA,workB));
thread1.start();
thread2.start();
}
/**
* @param args
*/
public static void main(String[] args) {
new TestClient();
}
}
class Thread1 implements Runnable {
private WorkA workA;
private WorkB workB;
public Thread1(WorkA workA, WorkB workB) {
this.workA = workA;
this.workB = workB;
}
public void run() {
for(int i=0;i<100;i++) {
System.out.println("Calling WorkA.method1()..." +i);
this.workA.method1();
}
}
}
class Thread2 implements Runnable {
private WorkA workA;
private WorkB workB;
public Thread2(WorkA workA, WorkB workB) {
this.workA = workA;
this.workB = workB;
}
public void run() {
for(int i=0;i<100;i++) {
System.out.println("Calling WorkB.method3()..." +i);
this.workB.method3();
}
}
}
|
When I ran this program , following is the output I observed:
Calling WorkA.method1()...0
Inside WorkB.method2....
Calling WorkA.method1()...1
Inside WorkB.method2....
Calling WorkA.method1()...2
Inside WorkB.method2....
Calling WorkA.method1()...3
Inside WorkB.method2....
Calling WorkA.method1()...4
Inside WorkB.method2....
Calling WorkA.method1()...5
Inside WorkB.method2....
Calling WorkA.method1()...6
Inside WorkB.method2....
Calling WorkA.method1()...7
Inside WorkB.method2....
Calling WorkA.method1()...8
Inside WorkB.method2....
Calling WorkA.method1()...9
Calling WorkB.method3()...0
Inside WorkB.method2....
Calling WorkA.method1()...10
|
This means , the moment Thread2 calls WorkB.method3(), it acquires the lock for
WorkB and tries to acquire lock/monitor for WorkA, but WorkA is already getting
used by Thread1. So both Thread1 and Thread2 qaits indefinitely, causing a
Thread Deadlock.
Similarly for Scenario 2: When both WorkA and WorkB are not Singleton,
but both the Threads are using/sharing same instances of WorkA and WorkB
some how. It will be more clear as you go through the following code as well:
WorkA.java
package demo;
public class WorkA {
private WorkB workB;
public void setWorkB(WorkB workB) {
this.workB = workB;
}
public synchronized void method1() {
workB.method2();
}
public synchronized void method4() {
System.out.println("Inside WorkA.method4....");
}
}
WorkB.java
package demo;
public class WorkB {
private WorkA workA;
public void setWorkA(WorkA workA) {
this.workA = workA;
}
public synchronized void method2() {
System.out.println("Inside WorkB.method2....");
}
public synchronized void method3() {
workA.method4();
}
}
TestClient.java
package demo;
public class TestClient {
public TestClient() {
WorkA workA = new WorkA();
WorkB workB = new WorkB();
workA.setWorkB(workB);
workB.setWorkA(workA);
Thread thread1 = new Thread(new Thread1(workA,workB));
Thread thread2 = new Thread(new Thread2(workA,workB));
thread1.start();
thread2.start();
}
/**
* @param args
*/
public static void main(String[] args) {
new TestClient();
}
}
class Thread1 implements Runnable {
private WorkA workA;
private WorkB workB;
public Thread1(WorkA workA, WorkB workB) {
this.workA = workA;
this.workB = workB;
}
public void run() {
for(int i=0;i<100;i++) {
System.out.println("Calling WorkA.method1()..." +i);
this.workA.method1();
}
}
}
class Thread2 implements Runnable {
private WorkA workA;
private WorkB workB;
public Thread2(WorkA workA, WorkB workB) {
this.workA = workA;
this.workB = workB;
}
public void run() {
for(int i=0;i<100;i++) {
System.out.println("Calling WorkB.method3()..." +i);
this.workB.method3();
}
}
}
|
This scenario is showing following output as shown above to me.
Even if we have synchronized methods in Bean in this example,
I can avoid Deadlock in case of Threads accessing these objects just
by creating separate instance of beans for each Thread, so that all
Threads can work separately.
If anyone has some inputs to share, please write to me by using following
comment form, and after review, if found okay, I shall publish your
comment on this, in this Page.
All source code are provided "AS IS" and for reading purpose only.
 | Author of this article/writeup has expressed his/her willingness |
to help or guide users with any technical difficulties he/she faces
while working with the example code environment setting up, running
and resolving any such exception raised during compile or at runtime.
You may ask for any technical doubt or seek technical help related to
this article by using following form to reach for technical help
from the Author for FREE.
This article's Author shall be reading your request and responding
within reasonable time (no resolution timeframe defined as such).
|
|
|
Commented By -> guddu | Hi,
Nice example!!
Can you show some example code in which it shows how to
prevent Thread Deadlock while using Java Platform??
Thanks anyways |
| | |
Commented By -> chitra | its good |
| | |
Commented By -> gunasekaran | Mind boggling concept.....Explained clearly......Thank u..! |
| | |
Commented By -> sunil | Hi,
I'm facing a deadlock scenario in java
messaging. Could you please include any example
of transaction deadlock in Java messaging
context.
Thanks |
| | |
Commented By -> Amit | The same example seems to be working when
there are separate work A and work B is
being provided to two separate threads,
as shown in this code below:
Just to say the TestClient is modified a
little bit in the constructor code only.
demo.WorkA.java
package demo;
public class WorkA {
private WorkB workB;
public void setWorkB(WorkB workB) {
this.workB = workB;
}
public synchronized void method1() {
workB.method2();
}
public synchronized void method4() {
System.out.println("Inside WorkA.method4....");
}
}
|
demo.WorkB.java
package demo;
public class WorkB {
private WorkA workA;
public void setWorkA(WorkA workA) {
this.workA = workA;
}
public synchronized void method2() {
System.out.println("Inside WorkB.method2....");
}
public synchronized void method3() {
workA.method4();
}
}
|
and
demo.TestClient.java
package demo;
public class TestClient {
public TestClient() {
WorkA workA = new WorkA();
WorkB workB = new WorkB();
workA.setWorkB(workB);
workB.setWorkA(workA);
Thread thread1 = new Thread(new Thread1(workA,workB));
WorkA workA1 = new WorkA();
WorkB workB1 = new WorkB();
workA1.setWorkB(workB1);
workB1.setWorkA(workA1);
Thread thread2 = new Thread(new Thread2(workA1,workB1));
thread1.start();
thread2.start();
}
/**
* @param args
*/
public static void main(String[] args) {
new TestClient();
}
}
class Thread1 implements Runnable {
private WorkA workA;
private WorkB workB;
public Thread1(WorkA workA, WorkB workB) {
this.workA = workA;
this.workB = workB;
}
public void run() {
for(int i=0;i<100;i++) {
System.out.println("Calling WorkA.method1()..." +i);
this.workA.method1();
}
}
}
class Thread2 implements Runnable {
private WorkA workA;
private WorkB workB;
public Thread2(WorkA workA, WorkB workB) {
this.workA = workA;
this.workB = workB;
}
public void run() {
for(int i=0;i<100;i++) {
System.out.println("Calling WorkB.method3()..." +i);
this.workB.method3();
}
}
}
|
It is working as expected , how about you?? |
| | Are you interested in solving a very interesting Technology Stack while Playing this Game 
|
|
| Home >>> Your Questions on Java >>> Thread Deadlock Java >>> Example Java Thread Deadlock |
|
|
Visitor/User referred related external URL:
(Visible upon review and approved by this site Administrator)
|
|
|
|
|
<- requires login | Log in or Register | |
Copyright © 2008-2009, Interview-Questions-Tips-Forum, All Rights Reserved. | CONTACT PRIVACY POLICY DISCLAIMER |
 |
Terms of Use and Disclaimer :
This web site provides some of the information about various technologies, example
code, tips, tutorials etc. Like any printed materials, content of these pages may
become out of date over a period of time. Therefore all visitor/users of this web
site are requested/advised to refer to the originating parties/sources for the
latest changes and happenings for detailed information. This information is not
intended to be a substitute for the original reference provided by the originating
parties/sources.
By accessing and using this website in any ways, including, without
limitation, browsing the website pages, using any information, using any content and/or
downloading any materials, you agree to and are bound by the terms of use
described in this page and Usage Terms and Conditions.
If you do not agree to all of
the terms and conditions contained in the terms of use described in this
page and Usage Terms and Conditions, do not use this
website in any manner. If you are using the website on behalf of your
employer, you represent that you are authorized to accept these Terms of Use
on your employer's behalf.
All Trademarks are property of their respective owner. Appropriate measure is being
taken for providing accurate and up-to-date information but like any printed materials,
these blog(s)/contents may eventually be outdated one day, so if you are using any
of these information, please refer original content/documentation from respective sources.
And under no circumstances shall the Author of these contents and/or this web site
be liable for any loss, damage, expense incurred or suffered which is claimed to have
occurred because of usage of the contents of this web site.
If you have any questions/queries/feedback/suggestions then please write to this web
site owner at contact.
|  |
|
|
|
|
|