Possible outputs: X0Y1X2Y3X4Y5, X0X1X2Y3Y4Y5 Explanation: The C.i method is synchronized so the value returned by C.i is always unique. I rewrote the program to remove the "synchronized" keyword, run the for loop 1000000 times to check if the C.i was unique. I got 1000000 unique C.i(s). My question is that since Thread t1 and t2 use the same object c as their parameter, the "synchronized" keyword is meaningful here?
the method that is synchronized is an instance method which means it belongs to the object itself, and since the object is used by 2 threads, then ONLY one thread can access the method at a certain time, since the thread will own the monitor on the object during the execution of the synchronized method. You probably get this behavior because the increment of the i variable is done in the same line of code that returns the value. The exam asks about what is garanteed according to the specifications of the Java Language, not what you get as an output, some of the JVM implementations, platforms might implement things differently, but what is in the specs is what should be known. So if you try 2 billion itteration and you get different unique i, it doesn't matter, cause the specs say that unless the method is synchronized, there is no guarantee that the i is going to be unique. To add, the purpose of the question I think is not about the synchronized modifier, but is about the guaranteed behavior of the JVM / thread scheduler. HTH [ November 26, 2002: Message edited by: Alfred Kemety ]
Even though the expression i++ appears to be a single instruction it is actually a series of several virtual machine code instructions. The value of i is pushed onto the stack before it is incremented and then the old value of i is popped off of the stack and returned. It is possible that both threads might push the old value of i onto the stack before one thread increments the value of i. If that happens, then both threads will read the same value for i. The main point of the question is synchronization but I can now see that the behavior of the postfix increment expression might be obscuring the main point. To avoid this problem in the future I think I'll change the method as follows.
Does this new version clear up the doubts?
Dan Chisholm<br />SCJP 1.4<br /> <br /><a href="http://www.danchisholm.net/" target="_blank" rel="nofollow">Try my mock exam.</a>
Joined: Aug 14, 2002
It sure does, specially with the yield()
Joined: Aug 30, 2002
Thanks a lot for all your reply, I understand this program now.