Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 11 of 11

Thread: Creating a Deadlock

  1. #1
    Java kindergarten chronoz13's Avatar
    Join Date
    Mar 2009
    Location
    Philippines
    Posts
    659
    Thanks
    177
    Thanked 30 Times in 28 Posts

    Default Creating a Deadlock

    i just finished a chapter in a book about the basics of Thread(threading).. and i want to focus myself on the deadlock issue so i can finish the chapter clearly,(im not yet into going to "heavy concurrency", i just want to understand some fundamentals crystal clear)..

    im trying to create or rather produce a deadlock scenario.. heres the code..
    public class DeadLockSample {
     
        private Foo foo;
        private Bar bar;
     
        public DeadLockSample() {
     
            foo = new Foo();
            bar = new Bar();
        }
     
        public static void main(String[] args) {
     
            Runnable job1 = new DeadLockSample().new Job1();
            Runnable job2 = new DeadLockSample().new Job2();
     
            Thread threadA = new Thread(job1, "Thread A");
            Thread threadB = new Thread(job2, "Thread B");
     
            threadA.start();
            threadB.start();
        }
     
        private class Job1 implements Runnable {
     
            @Override
            public void run() {
     
                foo.foo();
            }
        }
     
        private class Job2 implements Runnable {
     
            @Override
            public void run() {
     
                foo.foo();
            }
        }
     
        private class Foo {
     
            public synchronized void foo() {
     
                System.out.println(Thread.currentThread().getName() + " Enters foo()");
                System.out.println(Thread.currentThread().getName() + " will sleep...");
                System.out.println(Thread.currentThread().getName() + " locked the access to foo()..");
                try {
     
                    Thread.sleep(200);
                } catch (InterruptedException ex) {
     
                    ex.printStackTrace();
                }
     
                System.out.println(Thread.currentThread().getName() + " woke up!");
     
                bar.bar();
            }
        }
     
        private class Bar {
     
            public synchronized void bar() {
     
                System.out.println(Thread.currentThread().getName() + " Enters bar()");
                System.out.println(Thread.currentThread().getName() + " will sleep...");
                System.out.println(Thread.currentThread().getName() + " locked the access to bar()..");
     
                try {
     
                    Thread.sleep(200);
                } catch (InterruptedException ex) {
     
                    ex.printStackTrace();
                }
     
                System.out.println(Thread.currentThread().getName() + " woke up!");
            }
        }
    }

    the output
    Thread A Enters foo()
    Thread A will sleep...
    Thread A locked the access to foo()..
    Thread B Enters foo()
    Thread B will sleep...
    Thread B locked the access to foo()..
    Thread B woke up!
    Thread A woke up!
    Thread B Enters bar()
    Thread B will sleep...
    Thread B locked the access to bar()..
    Thread A Enters bar()
    Thread A will sleep...
    Thread A locked the access to bar()..
    Thread B woke up!
    Thread A woke up!
    based on what i understand(an A.B.C explanation on the book) a synchronized method will prohibit a multiple access from different threads..
    Thread-A enters foo(), so it should have the object lock or key, then it should be locked from other threads, then Thread-A sleeps, kicking it out of running state(back to runnable), making Thread-B(running) access foo(), then how come Thread-B access foo()? if it DOESNT hold the object key the Thread-A has? i just want to skip this part, and conitnue on other things that i need to study, i just want to ingest-digest this thing before i turn my face on other place, thanks for any help...

    edit: and Thread-A should not drop the key right?, until it finishes a call to the method, until then Thread-B could have the key to access foo()..
    Last edited by chronoz13; August 27th, 2012 at 05:00 AM.


  2. #2
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,042
    Thanks
    63
    Thanked 2,708 Times in 2,658 Posts

    Default Re: Creating a Deadlock

    Are the threads locking on the same object?
    Add some debug code to print out the class objects addresses: this
    Add a constructor to Foo that prints out its this value.
    If you don't understand my answer, don't ignore it, ask a question.

  3. The Following User Says Thank You to Norm For This Useful Post:

    chronoz13 (August 27th, 2012)

  4. #3
    Java kindergarten chronoz13's Avatar
    Join Date
    Mar 2009
    Location
    Philippines
    Posts
    659
    Thanks
    177
    Thanked 30 Times in 28 Posts

    Default Re: Creating a Deadlock

    Are the threads locking on the same object?
    I dont exactly understand what you mean by this.. all i understand for now(from what i assume) is one of them should be locked and the other one is not

    but like what you have said, i added another print statement on the top of each method(foo & bar) block to display the addresses

    and this is what i've got
    Constructor: book.headFirstJava.chapter15MakeAConnection.DeadLockSample$Foo@27013985 Thread access by..main
     
    Constructor: book.headFirstJava.chapter15MakeAConnection.DeadLockSample$Foo@71988d36 Thread access by..main
     
    Thread B Enters foo() Object Address: book.headFirstJava.chapter15MakeAConnection.DeadLockSample$Foo@71988d36
    Thread B will sleep...
    Thread B locked the access to foo()..
    Thread A Enters foo() Object Address: book.headFirstJava.chapter15MakeAConnection.DeadLockSample$Foo@27013985
    Thread A will sleep...
    Thread A locked the access to foo()..
    Thread B woke up!
    Thread A woke up!
    book.headFirstJava.chapter15MakeAConnection.DeadLockSample$Bar@10ed7f5c
    book.headFirstJava.chapter15MakeAConnection.DeadLockSample$Bar@584479b2
    Thread B Enters bar() Object Address: book.headFirstJava.chapter15MakeAConnection.DeadLockSample$Bar@10ed7f5c
    Thread B will sleep...
    Thread A Enters bar() Object Address: book.headFirstJava.chapter15MakeAConnection.DeadLockSample$Bar@584479b2
    Thread A will sleep...
    Thread B locked the access to bar()..
    Thread A locked the access to bar()..
    Thread B woke up!
    Thread A woke up!
    is it because each thread has "EACH OWN" object "REFERENCE" being used? for every call to foo()? and each of it "HAS" lock, that the other one doesnt need to get?

  5. #4
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,042
    Thanks
    63
    Thanked 2,708 Times in 2,658 Posts

    Default Re: Creating a Deadlock

    each thread has "EACH OWN" object "REFERENCE"
    Yes.
    The print out shows that there are two Foo objects, one for each thread. For synchronize to work, there must be one object that all methods use.

    For a quick and dirty test, make the foo variable static. Then both threads will be using the one object.
    If you don't understand my answer, don't ignore it, ask a question.

  6. #5
    Java kindergarten chronoz13's Avatar
    Join Date
    Mar 2009
    Location
    Philippines
    Posts
    659
    Thanks
    177
    Thanked 30 Times in 28 Posts

    Default Re: Creating a Deadlock

    ok ok wait.. i should be missing something here, maybe the book really stripped everything down from "basic" to "building-blocks thing"

    1.) based on my code, I only have 1 foo instance, how come it becomes 2 references? i know that every thread has its own "stack", but i suspect that my foo instance is unique to the "heap"(only 1), how come it had 2 references? is it because i have 2 Runnable(job) instances passed respectively to 2 Threads(worker)?, thats why each thread makes another reference?

    2.)
    make the foo variable static
    i put a static identifier on the declaration of foo instance, but everything works the same..


    and thank you again for giving me a half-step forward..

  7. #6
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,042
    Thanks
    63
    Thanked 2,708 Times in 2,658 Posts

    Default Re: Creating a Deadlock

    I only have 1 foo instance, how come it becomes 2
    The code creates two instances with the following statements:
    Runnable job1 = new DeadLockSample().new Job1();
    Runnable job2 = new DeadLockSample().new Job2();

    but everything works the same..
    I didn't for me. Here's my output with a static foo:
    Running: java DeadLockSample

    Foo DeadLockSample$Foo@9b6976 <<<<<<<<<<<<<< This one not used
    Foo DeadLockSample$Foo@1dfa490
    Thread A Enters foo() DeadLockSample$Foo@1dfa490
    Thread A will sleep...
    Thread A locked the access to foo()..
    Thread A woke up!
    Thread A Enters bar()
    Thread A will sleep...
    Thread A locked the access to bar()..
    Thread A woke up!
    Thread B Enters foo() DeadLockSample$Foo@1dfa490
    Thread B will sleep...
    Thread B locked the access to foo()..
    Thread B woke up!
    Thread B Enters bar()
    Thread B will sleep...
    Thread B locked the access to bar()..
    Thread B woke up!

    0 error(s)
    If you don't understand my answer, don't ignore it, ask a question.

  8. The Following User Says Thank You to Norm For This Useful Post:

    chronoz13 (August 27th, 2012)

  9. #7
    Java kindergarten chronoz13's Avatar
    Join Date
    Mar 2009
    Location
    Philippines
    Posts
    659
    Thanks
    177
    Thanked 30 Times in 28 Posts

    Default Re: Creating a Deadlock

    oh yes i forgot this part, i put myself in my own deadlock, i forgot im using an enclosing instance..
    The code creates two instances with the following statements:
    Runnable job1 = new DeadLockSample().new Job1();
    Runnable job2 = new DeadLockSample().new Job2();


    "thread schedulers"? if its the reason then... just like what the book says, and references i looked in the web, Thread schedulers are not reliable most especially on different JVMs on DIFFERENT platforms.. is that why i cant produce the DeadLock thing on my code? using what you suggest, by making the foo instance static?

    ill repost the codes again, i dont know if this exactly what you mean to me to do
    public class DeadLockSample {
     
        private static Foo foo = new Foo();
        private static Bar bar = new Bar();
     
        public static void main(String[] args) {
     
            Runnable job1 = new DeadLockSample().new Job1();
     
            Thread threadA = new Thread(job1, "Thread A");
            Thread threadB = new Thread(job1, "Thread B");
     
            threadA.start();
            threadB.start();
        }
     
        private class Job1 implements Runnable {
     
            @Override
            public void run() {
     
                foo.foo();
            }
        }
     
        private static class Foo {
     
            public synchronized void foo() {
     
                System.out.println(Thread.currentThread().getName() + " Enters foo() " + this);
                System.out.println(Thread.currentThread().getName() + " will sleep...");
                System.out.println(Thread.currentThread().getName() + " locked the access to foo()..");
     
                try {
     
                    Thread.sleep(200);
                } catch (InterruptedException ex) {
     
                    ex.printStackTrace();
                }
     
                System.out.println(Thread.currentThread().getName() + " woke up!");
     
                bar.bar();
            }
        }
     
        private static class Bar {
     
            public synchronized void bar() {
     
                System.out.println(Thread.currentThread().getName() + " Enters bar() " + this);
                System.out.println(Thread.currentThread().getName() + " will sleep...");
                System.out.println(Thread.currentThread().getName() + " locked the access to bar()..");
     
                try {
     
                    Thread.sleep(200);
                } catch (InterruptedException ex) {
     
                    ex.printStackTrace();
                }
     
                System.out.println(Thread.currentThread().getName() + " woke up!");
            }
        }
    }

    or is there any other way to make this code of mine, to produce a deadlock? im starting to deplete my solutions and ideas at my current understanding..

    [edit] oh wait.. sorry i posted the older code one
    Last edited by chronoz13; August 27th, 2012 at 12:12 PM.

  10. #8
    Super Moderator helloworld922's Avatar
    Join Date
    Jun 2009
    Posts
    2,896
    Thanks
    23
    Thanked 619 Times in 561 Posts
    Blog Entries
    18

    Default Re: Creating a Deadlock

    The problem is you only have one object to lock on. A deadlock situation requires at least 2 locks. Synchronized methods acquire a lock on the current object.

    The simplest situation to create a deadlock is to use two lock objects. The program flow is similar to this:

    Thread A acquires lock1.
    Thread B acquires lock2.
    Thread A attempts to acquire lock2.
    Thread B attempts to acquire lock1.

    Thread A and B are now deadlocked.
    Last edited by helloworld922; August 27th, 2012 at 12:41 PM.

  11. The Following User Says Thank You to helloworld922 For This Useful Post:

    chronoz13 (August 28th, 2012)

  12. #9
    Java kindergarten chronoz13's Avatar
    Join Date
    Mar 2009
    Location
    Philippines
    Posts
    659
    Thanks
    177
    Thanked 30 Times in 28 Posts

    Default Re: Creating a Deadlock

    A deadlock situation requires at least 2 locks

    Thread A acquires lock1.
    Thread B acquires lock2.
    Thread A attempts to acquire lock2.
    Thread B attempts to acquire lock1.
    - thank you for this.. i manage to make a newer version producing a deadlock(so it is still possible with multiple references), but im still puzzled why norm manage to make a deadlock using those codes i posted, but not in my machine, still.. a Thread scheduler issue?

    public class DeadLockSample {
     
        public static void main(String[] args) {
     
            final Foo foo1 = new Foo();
            final Foo foo2 = new Foo();
     
            new Thread(new Runnable() {
                public void run() {
     
                    foo1.foo1(foo2);
                }
            }).start();
     
            new Thread(new Runnable() {
                public void run() {
     
                    foo2.foo2(foo1);
                }
            }).start();
        }
     
        private static class Foo {
     
            public synchronized void foo1(Foo foo) {
     
                System.out.println(Thread.currentThread().getName() + " Enters foo1() " + this);
                System.out.println(Thread.currentThread().getName() + " will sleep...");
                System.out.println(Thread.currentThread().getName() + " locked the access to foo()..");
     
                try {
     
                    Thread.sleep(200);
                }
                catch (InterruptedException ex) {
     
                    ex.printStackTrace();
                }
     
                foo.foo2(foo);
            }
     
            public synchronized void foo2(Foo foo) {
     
                System.out.println(Thread.currentThread().getName() + " Enters foo2() " + this);
                System.out.println(Thread.currentThread().getName() + " will sleep...");
                System.out.println(Thread.currentThread().getName() + " locked the access to foo()..");
     
                try {
     
                    Thread.sleep(200);
                }
                catch (InterruptedException ex) {
     
                    ex.printStackTrace();
                }
     
                foo.foo1(foo);
            }
        }
    }

    if there is more simple way than this i did.. i would accept further changes in my code

  13. #10
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,042
    Thanks
    63
    Thanked 2,708 Times in 2,658 Posts

    Default Re: Creating a Deadlock

    why norm manage to make a deadlock using those codes i posted
    I didn't make a deadlock. The two threads ran to completion.
    If you don't understand my answer, don't ignore it, ask a question.

  14. #11
    Java kindergarten chronoz13's Avatar
    Join Date
    Mar 2009
    Location
    Philippines
    Posts
    659
    Thanks
    177
    Thanked 30 Times in 28 Posts

    Default Re: Creating a Deadlock

    ahh sorry. i thought you mean by

    I didn't for me. Here's my output with a static foo:
    that output, you made it deadlock.. anyway thank you again for the helps

Similar Threads

  1. [SOLVED] Banker Deadlock detection algorith going haywire and likely a stack overflow error
    By javapenguin in forum What's Wrong With My Code?
    Replies: 2
    Last Post: April 23rd, 2012, 05:23 PM
  2. Deadlock!!
    By mulligan252 in forum Threads
    Replies: 7
    Last Post: October 16th, 2011, 08:08 PM
  3. Creating and implementing class for creating a calendar object
    By kumalh in forum Object Oriented Programming
    Replies: 3
    Last Post: July 29th, 2011, 08:40 AM
  4. How to avoid the Deadlock in the below program
    By murali1253 in forum Threads
    Replies: 0
    Last Post: April 15th, 2010, 05:35 PM
  5. creating a gui
    By rsala004 in forum AWT / Java Swing
    Replies: 2
    Last Post: July 21st, 2009, 02:17 AM