Hi,
This is question 37 from the diagnostic quiz in Exam Lab
The possible answers are :
A) compilation fails
B) Prints A-A-B-B-C-C
C) Prints A-B-C-A-B-C
D) Result is unpredictable
E) Exception at runtime.
The answer is D. The explanation give is "a new
string object is created every time because of the keyword new. Therefore the lock of an instance of the given String will be owned by the first
thread; and another instance of the given String will be owned by the second thread.
However, in the K&B book page 433-434 it says "If a match is found, the reference to the new literal is directed to the existing String, and no new String literal object is created."
In the above example, wouldn't the string "a" be in the string pool, meaning it's the same object, and so synchronization would work and the output would be A-B-C-A-B-C
Does the new String("a") causes a new String in the string pool? So if you did the following:
new String("a");
new String("a");
new String("a);
would you end up with 3 String objects in the String pool all representing the letter a?