Synchronized Methods and Synchronized Blocks - Coddicted

Synchronized Methods and Synchronized Blocks

If you declare a method to be synchronized, then the entire body of the method becomes synchronized; if you use the synchronized block, however, then you can surround just the “critical section” of the method in the synchronized block, while leaving the rest of the method out of the block.
 
If the entire method is part of the critical section, then there effectively is no difference. If that is not the case, then you should use a synchronized block around just the critical section. The more statements you have in a synchronized block, the less overall parallelism you get, so you want to keep those to the minimum.
 
The other is that you can acquire a lock on other objects than this
 
class Something 
{
    public synchronized void doSomething() 
    {
        …
    }
 
    public static synchronized void doSomethingStatic() 
    {
        …
    }
}
 
is equivalent to
 
class Something 
{
    public void doSomething() 
    {
            synchronized(this) 
    {
                …
            }
     }
 
    public static void doSomethingStatic() 
    {
        synchronized(Something.class) 
{
                …
        }
    }
}

Back To Top
Rate this post

Leave a Reply