This week's giveaway is in the EJB and other Java EE Technologies forum. We're giving away four copies of EJB 3 in Action and have Debu Panda, Reza Rahman, Ryan Cuprak, and Michael Remijan on-line! See this thread for details.
When fragment I or fragment II is inserted in line 4, which are true? (Choose all that apply.)
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
F is correct. With fragment I, the chat method is synchronized, so the two threads can't swap back and forth. With either fragment, the first output must be yo. A, B, C, D and E are incorrect based on the above.
In the book it is stated that the correct answer is F(and part of it is): With either fragment, the first output must be yo.
I have made some test because I couldn't explain to myself why is it certain that "yo" will be the first output and received output that is in contrary: dude dude yo yo.
My assumption is that if the second fragment is used(without synchronization) it is not possible to predict the output. Am I wrong here?
If the first thread stores its id in the flag var and right after that the second starts executing the chat method it would not print yo as a first statement.
I would be really grateful if someone can explain to me what am I missing here?
Hello guys...to the best of my knowledge...This program as-it-stands the first output could be dude, that depends on the decision of the scheduler in the JVM.
If both threads have concurrent access to the non-synchronized chat method, there's NO guarantee that line 8 will always return true -at the first instance-, hence there is a possibility that the first output is "dude".
In Your Pursuit Towards Certification, NEVER Give Up.