Pascal's Weblog
The Grid...



Archives
« November 2009
SunMonTueWedThuFriSat
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
     
       
Today
Click me to subscribe
Search

Links
 

Today's Page Hits: 19

« Remote and Serializa... | Main | And the solution... »
Friday Dec 15, 2006
A Thread issue...
What's wrong with this program? It did not run as expected, JConsole did not detect a deadlock, and FindBugs did not detect a problem (it did report not to use sleep with a lock held)

class Run1 implements Runnable {
  String s;
  boolean wait = true;
  Run1(String s) {
    this.s = s;
  }
  public synchronized void run() {
    System.out.println("run " + s);
    try {
      Thread.sleep(4000);
    } catch (InterruptedException ex) {
    }
    wait = false;
    System.out.println("notify for run " + s);
    notifyAll();
  }
  public synchronized void get() {
    while (true) {
      try {
        System.out.println("wait...");
        wait();
        if (!(wait)) break;
        System.out.println("recv notify...");
      } catch (InterruptedException ex) {
      }
    }
  }
}


public class TestThread {

  public synchronized void testIt() throws Exception {
    Run1 run1 = new Run1("1");
    Run1 run2 = new Run1("2");
    Thread t1 = new Thread(run1);
    t1.start();
    Thread t2 = new Thread(run2);
    t2.start();

    run1.get();
    run2.get();

  }

  public static void main(String[] args) throws Exception {
    TestThread t = new TestThread();
    t.testIt();
  }

}
Posted at 09:01AM Dec 15, 2006 by Pascal Ledru in Java  |  Comments[1]

Comments:

Since the entire methods are synchronized, it looks like Run1.get() does not get called until the lock held by Run1.run() is released.
This is not a deadlock. Rather, the notifyAll() happens before the wait(). So you end up waiting indefinitely.

Posted by SB on December 15, 2006 at 03:02 PM PST #

Post a Comment:
  • HTML Syntax: NOT allowed