GeeCON Prague 2014*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes nikos thread question Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "nikos thread question" Watch "nikos thread question" New topic
Author

nikos thread question

Raju Champaklal
Ranch Hand

Joined: Dec 10, 2009
Posts: 521


why is the answer not guarenteed to be 2000? arent setNumber and getNumber synchronized...is this becasue both the threads have entered the run method and started the loop...and once the first thread finishes with setNumber and getNumber the other one can start it enter too...........?


scjp 1.6 91%, preparing for scmad
"Time to get MAD now.. we will get even later"....by someone unknown
Martin Sergeant
Greenhorn

Joined: May 20, 2003
Posts: 24
The problem is that although the setNumber and getNumber methods are synchronized,
the action of getting and setting the number is not atomic. Therfore it is possible
for a thead call getNumber and before it has time to call setnumber , another thread
may nip in and call getNumber, thus both threads will call setnumber using the same
number. This can be avoided by combining setNumber and getNumber in one
synchronized method


Martin
 
GeeCON Prague 2014
 
subject: nikos thread question