Siva Masilamani wrote:Then could you please explain what they are trying to point out here
"with either fragment the first output must be Yo"
Dudes instance created in go() has no synchronization associated with it. There is absolutely no guarantee which thread will execute flag = id first even when using synchronized keyword. It could be any of the threads who enter the block first.
I think it does not explain the doubt (which I'm having, too). Let's consider a following scenario using fragment 2 (no synchronization):
Let T1 and T2 be the threads.
After this flag == 1.
Then T2 takes the CPU and executes:
flag == 1, so it remains unchanged (assuming that flag's value is flushed).
Then, it executes
where id == 2 and flag == 1, so the output is "dude dude".
Then T1 starts again, printing "yo yo" in the loop. So the output is "dude dude yo yo" altogether. Am I wrong somewhere?
Joined: Sep 19, 2008
Adam you are almost right.But the value of id will not affect as it is the method local variable, each thread has its own copy and can not be changed by other thread but the problem lies with the static variable "flag".
Lets consider this scenario
Thread T1 execute the if expression but before it update the flag value with id thread T2 also executes the If expression,at this time both the thread enters the if block and T1 updates the flag with its own id say 1 and T2 updates the flag with id 2.
So when T1 executes the for loop it compares the values of flag with its own copy of ID value which is 1 and it did not match the value of flag as it has been updated by Thread t2 with its own ID.So T1 will print Dude Dude and T2 can print Yo Yo.
This is my understanding only,Please correct me if i am wrong.
Joined: Feb 18, 2008
Yes, Siva, I think we're making the same point (I know that the id variables are local - I just skipped the explanation that T1's id = 1 and T2's id = 2). Anyway, for me it's possible for the output to be "dude dude yo yo" - contrary to what the answer would suggest that "with either fragment the first output must be Yo".