Originally posted by Smita Sinha:
Then why does the code below, using a local String variable work when trying to synchronize.
...
Output is always: A1A2A3A1A2A3....B1B2B3B1B2B3...
i.e Thread "B" starts only after Thread "A" releases the lock, but the lock is a local object
Why does it work? Sheer luck. Or, sheer luck and fast computers.
The synchronized label is accomplishing nothing in this situtation. Don't believe me, comment it out and see what you get. I got the same output whether it was in there or not.
What is happening is that the first thread is started and, before it is timesliced out, it has completed all 15 iterations of its loop. Then, the next thread starts and it completes its 15 iterations. You're performing fairly short operations so it's doubtful that you'd see a timeslice cause a problem. If you were to let these loops go on infinitely, you may see some anomolies, but, of course, you'd have to look through an infinite amount of output to find it, too. :roll:
The key here is that
every object has its own lock which can be obtained for synchronization purposes. Since you have created two instances of the class GetLock and each instance has its own instance of the String lock, you have two
different instances of that String - one for each GetLock instance. Therefore, rather than both threads fighting for teh lock of a single object, they're getting locks from separate objects and will never fight over a lock.
As each thread is obtaining the lock from a local variable, there will never be a case when the thread tries to obtain the lock and won't be able to.
I hope that helps,
Corey