• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Non synchronized method

 
lidan liu
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Marshal
Pie
Posts: 21190
80
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
lidan liu
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you for the reply, appriciated
 
Daan Debie
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks, I came to the same conclusion! Good to know others found the mistake as well
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic