This week's book giveaway is in the OCAJP 8 forum. We're giving away four copies of OCA Java SE 8 Programmer I Study Guide and have Edward Finegan & Robert Liguori on-line! See this thread for details.
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
Joined: Jul 11, 2001
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.
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.