| Author |
semantic of synchronization
|
Ilja Preuss
author
Sheriff
Joined: Jul 11, 2001
Posts: 14112
|
|
Originally posted by adeel ansari: how about this? - when a thread is executing a synchronized block no other thread (using the same instance) can enter that block before it comes out. - or the other thread (using the same instance) can enter the block but can not access that particular object, which we specified in synchronized(obj), simultaneously. and wait for the turn. which one is right??
|
The soul is dyed the color of its thoughts. Think only on those things that are in line with your principles and can bear the light of day. The content of your character is your choice. Day by day, what you do is who you become. Your integrity is your destiny - it is the light that guides your way. - Heraclitus
|
 |
Ilja Preuss
author
Sheriff
Joined: Jul 11, 2001
Posts: 14112
|
|
|
The first is right. On entering the synchronized block, the thread is getting the monitor on the object you are synchronizing on. The monitor is released when leaving the synchronized block (or when calling wait()); Only one thread can hold the monitor to an object at the same time.
|
 |
David Harkness
Ranch Hand
Joined: Aug 07, 2003
Posts: 1646
|
|
Originally posted by adeel ansari: when a thread is executing a synchronized block no other thread (using the same instance) can enter that block before it comes out.
One important key to understanding synchronization is to realize that whether using a synchronized method or block you are always synchronizing on an object instance* -- not a method or block of code. The method or block only gives you the scope of the lock. If you have two different synchronized blocks that use the same object instance for their lock, they will block each other. If all of class A's methods are synchronized, calling a method of an instance of A will block any other synchronized blocks using that same instance of A. Again, the locked instance is what matters. * This is the same even for static synchronized methods. How? The methods lock the singleton Class instance.
|
 |
Mr. C Lamont Gilbert
Ranch Hand
Joined: Oct 05, 2001
Posts: 1170
|
|
the first is correct. the second is absolutely and completely false.
|
 |
Adeel Ansari
Ranch Hand
Joined: Aug 15, 2004
Posts: 2874
|
|
|
if i just remove this "(using the same instance)" from the first statement then what you people say.
|
 |
Daniel Mayer
Ranch Hand
Joined: Sep 09, 2004
Posts: 103
|
|
Originally posted by adeel ansari: if i just remove this "(using the same instance)" from the first statement then what you people say.
Then it becomes wrong.
|
 |
 |
|
|
subject: semantic of synchronization
|
|
|