aspose file tools*
The moose likes Threads and Synchronization and the fly likes Non synchronized method Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Java » Threads and Synchronization
Bookmark "Non synchronized method" Watch "Non synchronized method" New topic
Author

Non synchronized method

lidan liu
Greenhorn

Joined: Apr 30, 2011
Posts: 2
Hi
I have been preparing the JSCP exam and reading the book: sun certified programmer for java 6 study guide
I have a problem regarding to Chapter 9 Thread self test 15. The question is:

And given these two fragments inserted at where it says "insert code here":

I. synchronized void chat(long id){
II. void chat(long id){
which are true?
A. An exception is thrown at runtime
B. With fragment I, compilation fails
C. With fragment II, compilation fails
D. With fragment I, the output could be yo dude dude yo
E. With fragment I, the output could be dude dude yo yo
F. With fragment II, the output could be yo dude dude yo

The default answer explaination says: "With eigher fragment, the first output must be 'yo'"
I doubt that becuase the program sets the value of static varible "flag" before the for loop and then in the for loop the value is checked and output accordingly. Is it possible that thread one invokes chat() and sets the value first but before getting into the loop thread two graps CPU and eventually gets in the loop before thread one. And as a result of that the output may starts with "dude"?
I tried the code on my PC and the result does occasionally starts with "dude". So is the default answer wrong or did I miss something?
Cheers
Henry Wong
author
Sheriff

Joined: Sep 28, 2004
Posts: 18896
    
  40

lidan liu wrote:
The default answer explaination says: "With eigher fragment, the first output must be 'yo'"
I doubt that becuase the program sets the value of static varible "flag" before the for loop and then in the for loop the value is checked and output accordingly. Is it possible that thread one invokes chat() and sets the value first but before getting into the loop thread two graps CPU and eventually gets in the loop before thread one. And as a result of that the output may starts with "dude"?


Agreed. With no synchronization, ordering is not guaranteed.

Henry


Books: Java Threads, 3rd Edition, Jini in a Nutshell, and Java Gems (contributor)
lidan liu
Greenhorn

Joined: Apr 30, 2011
Posts: 2
Thank you for the reply, appriciated
Daan Debie
Greenhorn

Joined: Jan 05, 2012
Posts: 1
Thanks, I came to the same conclusion! Good to know others found the mistake as well
 
jQuery in Action, 2nd edition
 
subject: Non synchronized method