I have a question concerning the use of a synchronized method by two different objects. I have tried searching the forums for a similar question, but I wasn't able to find anything. If this question has already been answered, then a simple link to that
thread would be great. Thanks in advance for any help.
The code examples come from the
Sun Certified Programmer for Java 6 Study Guide by Kathy Sierra and Bert Bates.
In the chapter 9 Self
Test, there are two questions that have me confused. Question 17 (pg. 785) is:
Given:
And given these two fragments:
When either fragment I or fragment II is inserted at line 7, which are true? (Choose all that apply.)
A. Compilation fails
B. With fragment I, an exception is thrown
C. With fragment I, the output could be 4 2 4 2
D. with fragment I, the output could be 4 4 2 3
E. With fragment II, the output could be 2 4 2 4
Answer:
C and E are correct. E should be obvious. C is correct because even though move() is synchronized, it's being invoked on two different objects.
And now question 15 (pg. 783) from the same Self Test:
Given:
And given these two fragments:
When fragment I or fragment II is inserted at line 5, 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
Answer:
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.
My question is this: Based on the answer to question 17 (that there are two different objects, therefore they can access the synchronized method at the same time), shouldn't D also be a correct answer for question 15?
Thanks once again for any help.