Home | Contact Us | FAQ | Search & Site Map | Link to Us
Sign In | Join | Other 45 Sites in Network
HomeAnnouncementsWhite Papers
Discussion GroupsFirst AidDatabasesJavaBeansGUIJava 3DVirtual MachineCORBASecurityToolsGeneral
Java DirectoryOpen Source ProjectsSample Book ChaptersUser GroupsWeb Resources
Related Topics
Databases.NETMore Topics ...

Java Forum / General / November 2007

Tip: Looking for answers? Try searching our database.

Deadlocks

Thread view: 
getsanjay.sharma@gmail.com - 02 Nov 2007 20:23 GMT
Hello to all Java programmer out there.

I am currently reading about deadlocks and so wrote a small program
which would simulate a deadlock. But I have come across a very weird
behavior in the sense that it seems that Two threads are acquiring a
lock on an object at the same time. From what I know so far, each
object has a single lock object which a thread has to acquire to enter
the critical section. So why the given output which seems to say that
both Thread one and Thread two have acquired a lock on the same
object?

public class DeadLockTest
{
   public static void main(String[] args) throws Exception
   {
       Danger d = new Danger();
       One one = new One(d);
       one.setName("ThreadOne");
       Two two = new Two(d);
       two.setName("ThreadTwo");
       one.start();
       two.start();
   }
}

class One extends Thread
{
   private Danger d;

   public One(Danger d)
   {
       this.d = d;
   }

   public void run()
   {
       while (true)
       {
           try
           {
               Thread.sleep(100);
               d.write(10, 10);
           }
           catch (Exception e)
           {
               e.printStackTrace();
           }
       }
   }
}

class Two extends Thread
{
   private Danger d;

   public Two(Danger d)
   {
       this.d = d;
   }

   public void run()
   {
       while (true)
       {
           try
           {
               Thread.sleep(100);
               d.read();
           }
           catch (Exception e)
           {
               e.printStackTrace();
           }
       }
   }
}

class Danger
{
   static class Resource
   {
       int value;

       Resource(int value)
       {
           this.value = value;
       }

       int getValue()
       {
           return (value);
       }
   }

   private Resource one = new Resource(10);

   private Resource two = new Resource(20);

   public void read() throws Exception
   {
       synchronized (one)
       {
           System.out.println(Thread.currentThread().getName() + "
ACQUIRED lock on 'ONE'");
           Thread.sleep(400);
           synchronized (two)
           {
               System.out.println(Thread.currentThread().getName() +
" acquired lock on 'TWO'");
               System.out.println(Thread.currentThread().getName()
                       + " : The value is " + (one.getValue() +
two.getValue()));
           }
           System.out.println(Thread.currentThread().getName() + "
GAVE UP lock on 'TWO'");
       }
       System.out.println(Thread.currentThread().getName() + " GAVE
UP lock on 'ONE'");
   }

   public void write(int a, int b)
   {
       synchronized (one)
       {
           System.out.println(Thread.currentThread().getName() + "
ACQUIRED lock on 'ONE'");
           synchronized (two)
           {
               System.out.println(Thread.currentThread().getName() +
" ACQUIRED lock on 'TWO'");
               one.value = (one.value + a) % Integer.MAX_VALUE;
               two.value = (two.value + a) % Integer.MAX_VALUE;
               System.out.println(Thread.currentThread().getName()
                       + " : Setting values " + one.value + " and " +
two.value);
           }
           System.out.println(Thread.currentThread().getName() + "
GAVE UP lock on 'TWO'");
       }
       System.out.println(Thread.currentThread().getName() + " GAVE
UP lock on 'ONE'");
   }
}

/*
OUTPUT ->

[..]
ThreadOne ACQUIRED lock on 'ONE'
ThreadOne ACQUIRED lock on 'TWO'
ThreadOne : Setting values 20 and 30
ThreadOne GAVE UP lock on 'TWO'
ThreadOne GAVE UP lock on 'ONE'
>> ThreadTwo ACQUIRED lock on 'ONE'
ThreadTwo acquired lock on 'TWO'
ThreadTwo : The value is 50
ThreadTwo GAVE UP lock on 'TWO'
>> ThreadOne ACQUIRED lock on 'ONE'
ThreadOne ACQUIRED lock on 'TWO'
ThreadOne : Setting values 30 and 40
ThreadOne GAVE UP lock on 'TWO'
ThreadOne GAVE UP lock on 'ONE'
ThreadTwo GAVE UP lock on 'ONE'
[..]
*/

Links / Explanations / Comments / Suggestions would be really
appreciated.

Thanks and regards,
STS
Andrew Thompson - 02 Nov 2007 20:41 GMT
...
>public class DeadLockTest

..an SSCCE*, but for the line wrap**.  E.G....

>            System.out.println(Thread.currentThread().getName() + "
>ACQUIRED lock on 'ONE'");
...
>...Comments / Suggestions would be really
>appreciated.

Use the 'Text Width Check'** tool, with width set to 62
characters, to help avoid line-wrap in SSCCEs*.

* <http://www.physci.org/codes/sscce.html>
** <http://www.physci.org/twc.jnlp>

Signature

Andrew Thompson
http://www.athompson.info/andrew/

Zig - 02 Nov 2007 20:57 GMT
Hello,

That is a very insightfull test. However, the point of confusion I *think*  
is that the OS is free allocate processor time between threads with no  
guarantees, except that it will not allocate time to a thread currently  
waiting for a lock until that lock is available.

More to the point: once thread 1 releases lock ONE, the OS is free to  
transfer processor control to thread 2, which now aquires lock ONE, which  
can occur before thread 1 reaches:
System.out.println(Thread.currentThread().getName() + " GAVE UP lock on  
'ONE'");

Thus, a lock can only be held by one thread at a time, but they are not  
necessarily guaranteed to reach the println statements in the order you  
expect.

In your Danger.read method, you have a Thread.sleep() method between  
locks; if you make a similar sleep (or maybe Thread.yield()) in your  
Danger.write method just after you aquire lock ONE, but before the  
println, you should see the printlns occur in the expected order (99% of  
the time).

As an aside, I will point out that this class should not deadlock. Both  
threads use a consistant locking order ONE -> TWO. The danger of deadlock  
really shows up when you have a locking order violation, such as when  
thread 1 uses a locking order ONE -> TWO, and thread 2 uses the locking  
order TWO -> ONE. Thus, there is a potential that each thread is holding  
the lock the other thread requires, deadlocking the two threads.

HTH,

-Zig

> Hello to all Java programmer out there.
>
[quoted text clipped - 167 lines]
> Thanks and regards,
> STS

Signature

Using Opera's revolutionary e-mail client: http://www.opera.com/mail/

Daniel Pitts - 02 Nov 2007 21:20 GMT
> Hello to all Java programmer out there.
>
[quoted text clipped - 6 lines]
> both Thread one and Thread two have acquired a lock on the same
> object?

Here is a simple example of deadlock:
public class Dead implements Runnable {
  public static final Object lock = new Object();
  public static void main(String...args) throws Exception {
     synchronized (lock) {
         final Thread thread = new Thread(new Dead());
         thread.start();
         try {
             thread.join();
         } finally {
             System.exit(0);
         }
     }
  }

    public void run() {
        synchronized (lock) {
            System.out.println("This will never execute!");
        }
    }
}

I suggest you read the book Java Concurrency In Practice. It describes
common problems, correct solutions, and useful patterns for dealing with
concurrency.  It is the most complete and understandable writing on the
matter that I have come across.
<http://virtualinfinity.net/wordpress/technical-book-recommendations/java-concurr
ency-in-practice/
>

Signature

Daniel Pitts' Tech Blog: <http://virtualinfinity.net/wordpress/>

Patricia Shanahan - 02 Nov 2007 21:22 GMT
> Hello to all Java programmer out there.
>
[quoted text clipped - 6 lines]
> both Thread one and Thread two have acquired a lock on the same
> object?
...
> Links / Explanations / Comments / Suggestions would be really
> appreciated.
...

I think you may be over-interpreting your output. In particular, when
you see a "GAVE UP" line, it only means that thread gave up that lock at
some time between the last output from it and that point.

Patricia
Nigel Wade - 05 Nov 2007 09:47 GMT
> Hello to all Java programmer out there.
>
[quoted text clipped - 6 lines]
> both Thread one and Thread two have acquired a lock on the same
> object?

[snip]
> /*
> OUTPUT ->
[quoted text clipped - 23 lines]
> Thanks and regards,
> STS

I think the problem is your implicit assumption that after releasing a lock the
same thread continues execution and prints the line of text saying it gave up
the lock. This is not a valid assumption. The scheduler may well decide the
other thread has been waiting for some time and schedule that thread to run. So
the new thread prints its message saying it's got the lock before the original
thread gets to print its message saying it's released it.

If you want to guarantee that the prints to System.out occur in the correct
sequence they must also be guarded by the same synchronization object. That is,
instead of printing a message saying you've released the lock you should print
a message saying that the lock is about to be released.

Signature

Nigel Wade, System Administrator, Space Plasma Physics Group,
           University of Leicester, Leicester, LE1 7RH, UK
E-mail :    nmw@ion.le.ac.uk
Phone :     +44 (0)116 2523548, Fax : +44 (0)116 2523555

Ingo Menger - 05 Nov 2007 14:27 GMT
> Hello to all Java programmer out there.
>
[quoted text clipped - 6 lines]
> both Thread one and Thread two have acquired a lock on the same
> object?

In addition to what others write and in case you wanted to provoke a
deadlock: When all participiants try to ackquire locks for the same
objects *in the same order*, it is not easily possible to dead lock.
Try to lock the objects in different order and you may get something
like:
  Thread1 gets lock for object 2      Thread2 gets lock for object 1
  Thread1 waits for lock on obj1      Thread2 waits for lock on obj2


Free Magazines

Get these publications absolutely FREE for up to 12 months. There are no hidden fees and no obligation. Simply choose a title, complete the application form and submit it. Read more ...

Oracle MagazineNetwork ComputingComputer WorldBio-IT WorldeWeekInformation WeekInfosecurity
 
Sign In
Join
My Latest Posts
My Monitored Threads
My Blog
My Photo Gallery
My Profile
My Homepage

Start New Thread
Enable EMail Alerts
Rate this Thread



©2009 Advenet LLC   Privacy Policy - Terms of Use
This website includes both content owned or controlled by Advenet as well as content owned or controlled by third parties.