I'm just starting to learn Java, including servlets. I use Eclipse (Version: Helios Service Release 2) and GWT. Wrote a simple test (without GAE). The client on the GWT sends requests to the server. One of the requests makes wait() , and the other (at the time when the first hangs on wait) calls notifyAll() .

No reaction.

The one that called wait() (f3Server()) continues to wait until the specified timeout , and then returns the result to the client. The one that called notify (f2Server()) successfully returns the result. Call results are normally displayed. The number of such requests ( wait in parallel (in the above text, the output of this test is not)) does not affect anything.

 Date update = new Date(); public String f2Server(String []input) { // 'Будильник' priln("f2Serveer: "+Thread.currentThread().toString()+" id="+input[2]); update = new Date(); synchronized (update) { update.notifyAll(); } return Thread.currentThread().toString()+ " f2Server, "+input[0]+"<br>Arg: "+input[1]+"<br>"+ (input.length > 2? input[2]:""); } public String f3Server(String []input) { // Ждет события priln("f3Server: "+Thread.currentThread().toString()+" id="+input[2]); Date d = new Date(); try { /* while (d.getTime() > update.getTime()) { Thread.sleep(500); } */ synchronized (update) { update.wait(5000); } } catch (Exception ex) { priln("f3Server sleep exception " +Thread.currentThread().toString()+" id="+input[2]); } priln("f3server after sleep " +Thread.currentThread().toString()+" id="+input[2]); return Thread.currentThread().toString()+ " f3Server, "+input[0]+"<br>Arg: "+input[1]+"<br>"+ (input.length > 2? input[2]:""); } 

Debug printing on the console:

 f2Serveer: Thread[btpool0-0,5,main] id=1313503727340 f3Server: Thread[btpool0-0,5,main] id=1313503727340 f2Serveer: Thread[btpool0-2,5,main] id=1313503727340 f2Serveer: Thread[btpool0-2,5,main] id=1313503727340 f2Serveer: Thread[btpool0-2,5,main] id=1313503727340 f3server after sleep Thread[btpool0-0,5,main] id=1313503727340 

The update variable is really the same for all calls, as confirmed by the commented while() test (instead of synchronized (update) ) in f3Server() .

Explain, please, what is happening here?

    1 answer 1

    You called wait() on one object.

     synchronized (update) { update.wait(5000); } 

    and notifyAll() call on another:

     update = new Date(); synchronized (update) { update.notifyAll(); } 

    And the commented fragment worked, because at each iteration of the cycle there was a new call on the update link and each time an object was called, to which this link is currently pointing. wait() holds the lock on the original object.

    • Thank you, I will definitely check it out tomorrow, but I sense that it is. - avp pm
    • Checked, perfect. - avp