Forums Register Login

Non synchronized method

+Pie Number of slices to send: Send
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
1
+Pie Number of slices to send: Send
 

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
+Pie Number of slices to send: Send
Thank you for the reply, appriciated
+Pie Number of slices to send: Send
Thanks, I came to the same conclusion! Good to know others found the mistake as well
The two armies met. But instead of battle, they decided to eat some pie and contemplate this tiny ad:
a bit of art, as a gift, that will fit in a stocking
https://gardener-gift.com


reply
reply
This thread has been viewed 1323 times.
Similar Threads
Thread self test SCJP6
Thread synchronization problem K&B, SCJP 6 - chapter 9, question 15
about Thread(ch09 q15)
K&B chapter 9 Threads question 15
Question 15 chapter 9 of k&B
More...

All times above are in ranch (not your local) time.
The current ranch time is
Apr 16, 2024 08:47:56.