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: 12

« A Thread issue... | Main | CS 101 »
Friday Dec 15, 2006
And the solution...
A quick analysis of the code is:
Should be straightforward? but the program actually blocks.
Taking a closer look, here is what is going on:

The moral of this story is that as everyone knows it is way too easy to make this sort of mistakes. To make concurrent programming little bit easier, Java 1.5 introduced the java.util.concurrent package and several classes to ease the development of multi-threads applications. Looking back at our problem, we want to ensure the run method is executed first, then the get method. A possible solution (I just started learning about these new classes!) is to use the new CountDownLatch class:

Also, since we are not using the wait and notifyAll calls directly any longer it is not necessary to synchronized the run and get methods. The implementation of the class becomes:
class CRun1 implements Runnable {

  String s;
  CountDownLatch c = new CountDownLatch(1);

  CRun1(String s) {
    this.s = s;
  }

  public void run() {
    System.out.println("Lrun " + s);
    try {
      Thread.sleep(4000);
    } catch (InterruptedException ex) {
    } finally {
    }
    System.out.println("count down - notify for run " + s);
    c.countDown();
  }

  public void get() {
    while (true) {
      try {
        c.await();
        break;
      } catch (InterruptedException ex) {
      }
    }
    System.out.println("recv notify...");
  }
}
Posted at 09:52AM Dec 15, 2006 by Pascal Ledru in Java  |  Comments[0]

Comments:

Post a Comment:
  • HTML Syntax: NOT allowed