From page 291 of OCP Java SE 6 Programmer Practice Exams, question 25:
public class Stone implements Runnable { static int id = 1; public void run() { id = 1 - id; if (id == 0) pick(); else release(); } private static synchronized void pick() { System.out.print("P "); System.out.print("Q "); } private synchronized void release() { System.out.print("R "); System.out.print("S "); } public static void main(String[] args) { Stone st = new Stone(); new Thread(st).start(); new Thread(st).start(); } }
One of the answers is:
The output could be
P Q P Q
I marked this answer as correct. My reasoning:
run()
.1 - id
. Result is 0
. It is stored on the thread's stack. We are just about to save that 0
to static id
, but...run()
. Static id
is still 1
, so he executes method pick()
. P Q
is printed.0
from its stack and saves to static id
. So, the first thread also executes pick()
and prints P Q
.However, in the book it's written that this answer is incorrect:
It is incorrect because the line
id = 1 - id
swaps the value ofid
between0
and1
. There is no chance for the same method to be executed twice.
I don't agree. I think there is some chance for the scenario I presented above. Such swap is not atomic. Am I wrong?
Am I wrong?
Nope, you're absolutely right - as is your example timeline.
In addition to it not being atomic, it's not guaranteed that the write to id
will be picked up by the other thread anyway, given that there's no synchronization and the field isn't volatile.
It's somewhat disconcerting for reference material like this to be incorrect :(
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With