• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Tim Cooke
  • Liutauras Vilda
  • Jeanne Boyarsky
  • paul wheaton
Sheriffs:
  • Ron McLeod
  • Devaka Cooray
  • Henry Wong
Saloon Keepers:
  • Tim Holloway
  • Stephan van Hulst
  • Carey Brown
  • Tim Moores
  • Mikalai Zaikin
Bartenders:
  • Frits Walraven

Threads synchronization

 
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
As I was trying to understand better the behaviour of JVM, a issue came up.
I defined a Calculator thread which calculates a sum and makes the result available through the getTotal() method. The Reader thread keeps a reference to the Calculator and prints the result.
As I wanted the result to the be printed only after the calculation, Reader calls wait() before calling getTotal(). Calculator calls notify() as soon as the result is ready.
In the main method, one Calculator object and three Reader objects are instantiated. The source code is presented below:





Now the curious stuff: as notify() in called just once, at most one Reader thread would print the result. However, the program ended with the following output:

Thread-1 is waiting...
Thread-2 is waiting...
Thread-3 is waiting...
(Thread-1) total is: 45
(Thread-2) total is: 45
(Thread-3) total is: 45

Even if I leave out the line with the notify() call, the output is the same.
The program just worked as I expected after I modified the way the Calculator thread is started, changing c.start(); to new Thread(c).start();:

Thread-1 is waiting...
Thread-2 is waiting...
Thread-3 is waiting...
(Thread-1) total is: 45

How is it possible ? I thought the synchronization mechanism was independent of the way threads were created. May I consider this a spurious wakeup ?


Thanks in advance
 
author
Posts: 14112
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
The implementation of the Thread.join(long) method seems to suggest that a Thread calls notifyAll() on itself when it's finished. That would definitely explain the observed behaviour, wouldn't it?
 
Is this the real life? Is this just fantasy? Is this a tiny ad?
Gift giving made easy with the permaculture playing cards
https://coderanch.com/t/777758/Gift-giving-easy-permaculture-playing
reply
    Bookmark Topic Watch Topic
  • New Topic