Question

Question regarding deadlock in Java

Asked by: wrynn

http://java.sun.com/docs/books/tutorial/essential/concurrency/deadlock.html

can someone explain to me why each method is able to print out the first statement, but cannot ever call the returnBow()?

This Question has been solved and asker verified All Experts Exchange premium technology solutions are available to subscription members.

Subscribe now for full access to Experts Exchange and get

Instant Access to this Solution

  • Plus...
  • 30 Day FREE access, no risk, no obligation
  • Collaborate with the world's top tech experts
  • Unlimited access to our exclusive solution database
  • Never be left without tech help again

Subscribe Now

Asked On
2009-11-04 at 19:32:57ID24873401
Topics

New to Java Programming

,

Open Source Programming

,

Java Server Pages (JSP)

Participating Experts
4
Points
500
Comments
20

Trusted by hundreds of thousands everyday for fast, accurate and reliable tech support.

  • "The time we save is the biggest benefit of Experts Exchange to Warner Bros. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange." Mike Kapnisakis, Warner Bros.
  • "Our team likes having a resource that is more secure than just using Google and most experts using this service really know their stuff. It's nice to look here first versus using Google." Dayna Sellner, Lockheed Martin
  • "Anytime that I've been stumped with a problem, 9 out of 10 times Experts Exchange has either the accepted solution or an open discussion of the potential solution to the problem." Kenny Red, eBay Inc.

See what Experts Exchange can do for you.

Got a question?

We've got the answer.

Experts Exchange has been collecting answers to technology questions since 1996…3 million and counting! If you have a question, chances are we already have your answer.

Screenshot of Experts Exchange Knowledgebase

Need individual assistance?

Our experts are ready to help.

If you can't find the exact answer you're looking for, ask our exclusive community of 50,000 experts. You’ll get a personalized answer from a trusted professional.

Screenshot of Experts Exchange Knowledgebase

Want to learn from the best?

Read articles from industry experts.

Thousands of free tech tips, tricks, how-to’s and tutorials are available in our peer reviewed articles section. See for yourself how smart our experts are, no login required.

Screenshot of an Article

Working on a long term project?

Store your work and research.

Save solutions to your questions, answers you’ve discovered through searching plus helpful articles in your personal knowledgebase for easy future access.

Screenshot of Experts Exchange Knowledgebase

Access the answers to your technology questions today.

Subscribe Now

30-day free trial. Register in 60 seconds.

What Makes Experts Exchange Unique?

Members of the expert community talk about why the experience at Experts Exchange is different than what you will find anywhere else.

Trusted by the world's most respected brands.

image of each brand's logo

Faithfully serving IT professionals since 1996.

Experts Exchange Logo

Try it out and discover for yourself.

Subscribe Now

30-day free trial. Register in 60 seconds.

Related Solutions

  1. JAVA learning books
    I just downloaded JDK 1.2. Until I downloaded JAVA I have only programmed in SQL, VB, HTML, and QBasic. I have gone over Suns tutorial, and it is very good. But I want a book that will take me through step by step learning the JAVA language (structure, syntax, keywords, comma...
  2. good java tutorials?
    does anyone know of any good java tutorials?

Free Tech Articles

  1. WARNING: 5 Reasons why you should NEVER fix a computer for free.
    It is in our nature to love the puzzle. We are obsessed. The lot of us. We love puzzles. We love the challenge. We thrive on finding the answer. We hate disarray. It bothers us deep in our soul. W...
  2. SCCM OSD Basic troubleshooting
    SCCM 2007 OSD is a fantastic way to deploy operating systems, however, like most things SCCM issues can sometimes be difficult to resolve due to the sheer volume of logs to sift through and the dispe...
  3. Migrate Small Business Server 2003 to Exchange 2010 and Windows 2008 R2
    This guide is intended to provide step by step instructions on how to migrate from Small Business Server 2003 to Windows 2008 R2 with Exchange 2010. For this migration to work you will need the fo...
  4. Create a Win7 Gadget
    This article shows you how to create a simple "Gadget" -- a sort of mini-application supported by Windows 7 and Vista. Gadgets can be dropped anywhere on the desktop to provide instant information, ...
  5. Outlook continually prompting for username and password
    There have been a lot of questions recently regarding Outlook prompting for a username and password whilst using Exchange 2007. There are a few reasons why this would happen and I will try to cover t...
  6. Backup Exchange 2010 Information Store using Windows Backup
    There seems to be quite a lot of confusion around the ability to backup Exchange 2010 using the built in Windows Backup feature. This stems from the omission of this feature prior to Exchange 2007 s...

Cloud Class Webinars

  1. Avoiding Bugs in Microsoft Access
    Alison Balter takes and in-depth look at avoiding bugs in Access. In this webinar you will learn about using the immediate window to debug your applications, invoking the debugger, using breakpoints to troubleshoot, stepping through code, setting the next statement to execute, ...
  2. Top 10 Best New Features in Visio 2010
    Scott Helmers gives live demonstrations of the top 10 new features in Visio 2010. This webinar will teach you how to create compelling diagrams by adding shapes to the page with a single click, linking the shapes in a diagram to data in Excel (or SQL Server, or SharePoint), ...
  3. IT Consultant Business Secrets Revealed
    Michael Munger, Experts Exchange tech pro and IT consultant, pulls back the curtain on his very successful businesses and answers question on every IT consultant and business owner should know about. He shares secrets on what he did to solve the 5 most common problems in IT, ...
  4. Disaster Recovery and Business Continuity
    Quest CTO, Mike Billon, gives an overview of the steps involved in building a dunamic disaster recovery plan. Through case studies and an examination of software/hardware tooles for monitoring and testing, you'll gain a better understandin of where you are, where you want ...
  5. Organize Your Visio Diagrams with Containers and Lists
    Scott Helmers uses cross functional flowcharts, wireframe diagrams, data graphic legends and seating charts to teach you: how to ustilize all three new structured diagram components in Visio 2010, the best practices for organizeing shapes in previous version of Visio, how to organize ...
  6. How to Us Objects, Properties, Events and Methods in Microsoft Access
    Alison Dalter gives an in-depbth look at objects, properties, events and methods in Microsoft Access. In this webinar you will learn about using the object browser, referring to objects, working with properties and methods, working with object variables, understanding the ...

Join the Community

Give a Little. Get a Lot.

Join the community of experts here and help other tech pros by answering question in your area of expertise. You can earn FREE access to all Experts Exchange's premium features and resources.

Join the Community

Answers

 

by: a_bPosted on 2009-11-04 at 20:34:59ID: 25746800

It's because they are in a deadlock, waiting for each other to finish. Try executing this -

public class Deadlock {
    static 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 void bowBack(Friend bower) {
            System.out.format("%s: %s has bowed back to me!%n",
                    this.name, bower.getName());
        }
    } 
    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();
    }
}
                                              
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31:

Select allOpen in new window

 

by: Ravi_KallaPosted on 2009-11-04 at 20:37:59ID: 25746810

Let us imagine each operation is done in a time frame of one second.

Second1 : "Friend" object for "alphonse" is created

Second2 : "Friend" object for "gaston" is created

Second3 : "bow()" method is called by "alphonse" and this will run in an individual thread

Second4 : "bow()" method is called by "gaston" and this will run in an individual thread

Second5 : "bowBack()" method is called by both "alphonse" and "gaston" objects at the same time. Since, "bowBack()" is a synchronized method, only one instance of that method can run at a time. So, if two objects call a synchronized method approximately at same time, each thread will wait for another thread to finish its job with the synchronized method "bowBack()". This waiting will last for ever and is called as DeadLock.

 

by: a_bPosted on 2009-11-04 at 20:39:38ID: 25746816

@wrynn: That was a very good explanation by Ravi_Kalla

 

by: afibarraPosted on 2009-11-04 at 21:10:48ID: 25746930

public synchronized void bow(Friend bower) {
    System.out.format("%s: %s has bowed to me!%n",
    this.name, bower.getName());
    bower.bowBack(this);  //Here each Thread is waiting for the other to complete
}

 

by: afibarraPosted on 2009-11-04 at 21:12:35ID: 25746942

I´m so slow, Ravi_Kalla´s explanation is very good.

 

by: rrz@871311Posted on 2009-11-04 at 21:20:29ID: 25746966

Ravi_Kalla's  explanation is good.
But I think the example code is confusing. In the code a Friend does not bow on his own initiative. A bower bows only when a Friend's bow method is called.  To see how it really works without the deadlock, add a delay between the two thread starts. Try the code below here.  The output is
Alphonse: Gaston has bowed to me!
Gaston: Alphonse has bowed back to me!
Gaston: Alphonse has bowed to me!
Alphonse: Gaston has bowed back to me!

public class Deadlock {
    static 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 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();
        try{
             Thread.sleep(1000);
        }catch(InterruptedException ie){
                                        System.out.print("sleep Interrupted");
          }
        new Thread(new Runnable() {
            public void run() { gaston.bow(alphonse); }
        }).start();
    }
}

                                              
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
32:
33:
34:
35:
36:

Select allOpen in new window

 

by: rrz@871311Posted on 2009-11-04 at 22:42:26ID: 25747216

On second thought, maybe a better explanation of the code's behavior is that  if
one synchronized method in an object calls another synchronized method in the same object, then a deadlock will occur.

 

by: rrz@871311Posted on 2009-11-05 at 08:15:45ID: 25750993

Please ignor my last comment. I was tired and confused last night.

 

by: wrynnPosted on 2009-11-05 at 18:52:22ID: 25756263

im confused because the output i'm getting is

Alphonse: Gaston has bowed to me!
Gaston: Alphonse has bowed to me!

Suggesting that the 2nd thread was able to begin executing the synchronized method "bow" before the 1st thread was finished executing.  isnt that supposed to be impossible? i thought that synchronized means that no other thread can call the method until the other thread is finished?

 

by: wrynnPosted on 2009-11-05 at 18:53:28ID: 25756267

what is also confusing is how sometimes i get this output:

Gaston: Alphonse has bowed to me!
Alphonse: Gaston has bowed back to me!
Alphonse: Gaston has bowed to me!
Gaston: Alphonse has bowed back to me!


so there seems to be some random nature to deadlock. can someone explain why in this case there is random output?

 

by: afibarraPosted on 2009-11-05 at 19:02:56ID: 25756299

>im confused because the output i'm getting is

>Alphonse: Gaston has bowed to me!
>Gaston: Alphonse has bowed to me!

>Suggesting that the 2nd thread was able to begin executing the synchronized method "bow" before the >1st thread was finished executing.  isnt that supposed to be impossible? i thought that synchronized >means that no other thread can call the method until the other thread is finished?


That only happens if two threads are about to execute a synchronized method in a class, and BOTH threads are using the same instance of the class to invoke the method. In this case each thread is using its own instance.

 

by: Ravi_KallaPosted on 2009-11-05 at 19:04:45ID: 25756304

If the synchronized method "bowBack()" is called by two different threads at approximately same time, it will go into deadlock. Sometimes, the time difference at which the two threads call "bowBack()" will be more. In such cases, the programs run without deadlock.

>>so there seems to be some random nature to deadlock.

It behaves randomly because, threads run independently and there is no hard and fast rule which thread has to be given more preference... and so the the time difference at which the "bowBack()" is called. If time difference is more, it wont go to dead lock.

 

by: wrynnPosted on 2009-11-05 at 19:17:15ID: 25756345

i just found this link here: http://forums.sun.com/thread.jspa?forumID=54&threadID=5341448

and it says the same thing that i just saw afibarra write regarding it being two DIFFERENT instances and thus DIFFERENT locks being used.  and that the deadlock is because each method tries to cross over and grab the lock from the other object which is already locking itself.  

for whatever reason i did not notice that they were different instances.  and i was unaware of the rule regarding unique locks for each instance.

A confusing topic for even "veteran" java programmers.  thanks for all of your help.

 

by: wrynnPosted on 2009-11-05 at 19:20:44ID: 31650348

wow im impressed. im so glad i use experts exchange because i can rely on the very smart people on here who almost always have great suggestions and explanations.  great work guys, keep it up you are helping others SUCCEED!!

 

by: rrz@871311Posted on 2009-11-05 at 19:30:22ID: 25756395

> i thought that synchronized means that no other thread can call the method until the other thread is finished?  
As we see on this page
http://java.sun.com/docs/books/tutorial/essential/concurrency/syncmeth.html
we have
"When one thread is executing a synchronized method for an object, all other threads that invoke synchronized methods for the same object block (suspend execution) until the first thread is done with the object."  
In this example, we have two Friend objects. When each object is in its own bow method, it has  it has acquired the intrinsic lock for itself.
As we see on this page
http://java.sun.com/docs/books/tutorial/essential/concurrency/syncmeth.html  
we have
" When one thread is executing a synchronized method for an object, all other threads that invoke synchronized methods for the same object block (suspend execution) until the first thread is done with the object.  
So, this example each Friend is waiting for the other Friend.  They are both in their own bow method and are calling each others  bowback method. That is the deadlock.  

>what is also confusing is how sometimes i get this output:  
On the page that you linked to in your question it states
"When Deadlock runs, it's extremely likely that both threads will block when they attempt to invoke bowBack."
It all depends on whether one Friend starts and finishs before the other starts. Did you run the code I posted yesterday? I insert a time delay. That way the deadlock is always avoided.

 

by: afibarraPosted on 2009-11-05 at 19:34:54ID: 25756416

yw =)

 

by: Ravi_KallaPosted on 2009-11-05 at 19:37:55ID: 25756427

I feel that 100 points is very less for ID: 25746810 ... there are good appreciations but no good points :)

 

by: wrynnPosted on 2009-11-06 at 12:32:08ID: 25762777

i wanted to reward afibarra for pointing out the most confusing part which is that each instance of an object has its own separate lock for all its synchronized methods.  

but i guess i gave him too many points.  next time i will try to spread the points around more evenly.

 

by: wrynnPosted on 2009-11-06 at 12:47:44ID: 25762901

afibarra was able to explain *why* the bowback method was unable to be called.  because the instances had locked themselves during bow(), and that were able to have access to run each of their synchronized bow() methods because they were dealing with their own instance lock.  but once they try to call a synchronized method on the OTHER object instance, it is unable to do so because it is locked, so it must wait. and if both threads by chance call .bowback() at the same time they will both begin to wait indefinitely for the locks to be released but they never will.

 

 

by: rrz@871311Posted on 2009-11-06 at 13:39:25ID: 25763304

I think you got it now.    

20120131-EE-VQP-002

3 Ways to Join

30-Day Free Trial

The Experts

98% positive feedback on 31,087 answers since March 2000. angeliii is a Microsoft Most Valuable Professional for his work with MS SQL Server & Develoment.

He has also proven his knowledge of Visual Basic Programming, PHP Scripting and Oracle Databases.

The Experts

97% positive feedback on 10,752 answers since July 2000. lrmoore has more than 18 years experience in the networking industry.

The six-time Mircosoft MVPs specialties include firewalls, virtual private networking, and network management.

Testimonials

"...and excellent source for support... Kind of like having your very own IT dept." Electriciansnet

Testimonials

"I was apprehensive at signing up at first. However... it has already made my life as an IT administrator much easier." JaCrews

Testimonials

"WOW! You guys have great, active, and knowledgeable people on here." moore50

Business Clients

Business Clients

In the Press

"If you’ve got a question... Experts Exchange can supply an answer.”

In the Press

"...an invaluable aid for both IT professionals and those who require tech support."

In the Press

"where IT professionals provide quick answers on just about any topic"

Business Account Plans

Loading Advertisement...