What is the difference between a synchronized method and synchronized block in Java? [duplicate]
Asked Answered
R

6

38

What is the difference between a synchronized method and synchronized block in Java ?

I have been searching the answer on the Net, people seem to be so unsure about this one :-(

My take would be there is no difference between the two, except that the synch block might be more localized in scope and hence the lock will be of lesser time ??

And in case of Lock on a static method, on what is the Lock taken ? What is the meaning of a Lock on Class ?

Retaliate answered 19/7, 2009 at 13:45 Comment(2)
@try-catch-finally That is not a duplicate of this question; that question asks if a synchronized method provides exclusive access to the method only, or to the entire object.Cervantes
@MarkRotteveel You're right in terms of the different titles. On the other hand, the other question's answers cover the differences too: scoping the synchronized section to some statements (or not) and controlling where to lock on (or having no control on that).Marniemaro
A
46

A synchronized method uses the method receiver as a lock (i.e. this for non static methods, and the enclosing class for static methods). Synchronized blocks uses the expression as a lock.

So the following two methods are equivalent from locking prospective:

synchronized void mymethod() { ... }

void mymethod() {
  synchronized (this) { ... }
}

For static methods, the class will be locked:

class MyClass {
  synchronized static mystatic() { ... }

  static mystaticeq() {
    syncrhonized (MyClass.class) { ... }
  }
}

For synchronized blocks, you can use any non-null object as a lock:

synchronized (mymap) {
  mymap.put(..., ...);
}

Lock scope

For synchronized methods, the lock will be held throughout the method scope, while in the synchronized block, the lock is held only during that block scope (otherwise known as critical section). In practice, the JVM is permitted to optimize by removing some operations out of the synchronized block execution if it can prove that it can be done safely.

Ahl answered 19/7, 2009 at 13:50 Comment(3)
I read some time ago (lost the source) that synchronized on method can be easier to optimize internally by JVM than synchronized on block even if that block encapsulates the whole method body. Could be interesting micro-benchmark to try.Steve
In the lock scope, you probably meant "... while in the synchronized block, the lock is held only during the synchronized block" and not "... while in the synchronized method the lock is held only during the synchronized block"Gramps
@Gregory Mostizky According to this article, JVM creates less bytecode for a synchronized method when compared to a synchronized block. ibm.com/developerworks/java/library/j-5things15/…Lasley
P
9

A synchronized method is shorthand. This:

class Something {
    public synchronized void doSomething() {
        ...
    }

    public static synchronized void doSomethingStatic() {
        ...
    }
}

is, for all intents and purposes, equivalent to this:

class Something {
    public void doSomething() {
        synchronized(this) {
            ...
        }
    }

    public static void doSomethingStatic() {
        synchronized(Something.class) {
            ...
        }
    }
}

(Where Something.class is the class object for the class Something.)

So indeed, with a synchronized block, you can be more specific about your lock, and more fine-grained about when you want to use it, but other than that there's no difference.

Plasmolysis answered 19/7, 2009 at 13:50 Comment(0)
C
5

Yes, that is one difference. The other is that you can acquire a lock on other objects than this.

Cohen answered 19/7, 2009 at 13:50 Comment(0)
P
2

The key difference is this: 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.

Peccant answered 19/7, 2009 at 13:59 Comment(2)
Quick follow-up: Would that mean that a synchronized block is less expensive to use than a synchronized method?Separatist
If the synchronized block includes all the contents of the function, then there is no difference. However, if you use a synchronized block, you can surround just the critical section (perhaps leaving some of the computation out of the synchronized region). If you do that, your program will run faster.Peccant
Y
0

A synchronized method locks on the object instance the method is contained in.

Where as a synchronized block can lock on ANY object - typically a mutex obect defined as an instance variable. This allows more control over what locks are in operation.

Yorkist answered 19/7, 2009 at 13:53 Comment(0)
L
0

My take would be there is no difference between the two, except that the synch block might be more localized in scope and hence the lock will be of lesser time ??

Yes. You are right. Unlike synchronized methods, synchronized statements must specify the object that provides the intrinsic lock.

Example from java tutorial:

public void addName(String name) {
    synchronized(this) {
        lastName = name;
        nameCount++;
    }
    nameList.add(name);
}

Synchronized statements are also useful for improving concurrency with fine-grained synchronization. You can find good example on same tutorial page for below use case.

Suppose, for example, class MsLunch has two instance fields, c1 and c2, that are never used together. All updates of these fields must be synchronized, but there's no reason to prevent an update of c1 from being interleaved with an update of c2 — and doing so reduces concurrency by creating unnecessary blocking. Instead of using synchronized methods or otherwise using the lock associated with this, we create two objects solely to provide locks.

And in case of Lock on a static method, on what is the Lock taken ? What is the meaning of a Lock on Class ?

In this case, the thread acquires the intrinsic lock for the Class object associated with the class. Thus access to class's static fields is controlled by a lock that's distinct from the lock for any instance of the class.

When you make a method as synchronized ( non static ) :

It is not possible for two invocations of synchronized methods on the same object to interleave. When one thread is executing a synchronized method for an object, all other threads that invoke synchronized methods for the same object block (suspend execution) until the first thread is done with the object.

If you make a method as static synchronized :

It is not possible for two invocations of static synchronized methods on different objects of same class to interleave. When one thread is executing a static synchronized method for an object of Class A, all other threads that invoke static synchronized methods on any of objects of Class A block (suspend execution) until the first thread is done with the method execution.

You find better alternatives to synchronization in this SE question:

Avoid synchronized(this) in Java?

Laveta answered 13/9, 2016 at 17:55 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.