| Author |
Difference between synchronized method and synchrozed block
|
Anwar Hussain
Ranch Hand
Joined: Jul 24, 2009
Posts: 35
|
|
Hi,
Can some body explain the difference between synchronized method and synchrozed block.
Thanks
|
 |
Patricia Samuel
Ranch Hand
Joined: Sep 12, 2007
Posts: 300
|
|
|
See it here
|
 |
Anwar Hussain
Ranch Hand
Joined: Jul 24, 2009
Posts: 35
|
|
Patricia Samuel wrote:See it here
Its confusing me
|
 |
Patricia Samuel
Ranch Hand
Joined: Sep 12, 2007
Posts: 300
|
|
with a synchronized block you can choose what to synchronize on. With a synchronized method, an instance method always synchronizes on the instance, a static method always synchronizes on the class.
synchronized(this) can have any object you want to synchronize where as when a method is synchronized it will work with instance for which it is called.
|
 |
Anwar Hussain
Ranch Hand
Joined: Jul 24, 2009
Posts: 35
|
|
Patricia Samuel wrote:with a synchronized block you can choose what to synchronize on. With a synchronized method, an instance method always synchronizes on the instance, a static method always synchronizes on the class.
synchronized(this) can have any object you want to synchronize where as when a method is synchronized it will work with instance for which it is called.
So when a thread is in the middle of execution of the synchronized block with 'this' as argument , can another thread call a synchronzed method of that same object???
|
 |
Embla Tingeling
Ranch Hand
Joined: Oct 22, 2009
Posts: 237
|
|
Anwar Hussain wrote:So when a thread is in the middle of execution of the synchronized block with 'this' as argument , can another thread call a synchronzed method of that same object???
It doesn't matter whether a whole method is synchronized or just a block. Synchronized always means the synchronized code section can be run by one thread at a time only.
|
 |
Vivek Singh
Ranch Hand
Joined: Oct 27, 2009
Posts: 92
|
|
Anwar Hussain wrote:So when a thread is in the middle of execution of the synchronized block with 'this' as argument , can another thread call a synchronzed method of that same object???
Is equivalent to :-
Form K&B
"When you synchronize a method, the object used to invoke the method is the object whose lock must be acquired. But when you synchronize a block of code, you specify which object's lock you want to use as the lock, so you could, for example, use some third-party object as the lock for this piece of code. That gives you the ability to have more than one lock for code synchronization within a single object."
|
 |
 |
|
|
subject: Difference between synchronized method and synchrozed block
|
|
|