0

Possible Duplicate:
synchronized block vs synchronized method?

Hi all I was wondering is Snippet-A simply a syntax sugar for Snippet-B? :

Snippet A:

public synchronized void F() {
    //..code
}

Snippet B:

public void F() {
    synchronized (this) {
        //..code
    }
}

Or rather, what exactly is the difference between the two pieces of code above?

Community
  • 1
  • 1
Pacerier
  • 86,231
  • 106
  • 366
  • 634
  • 2
    See this: http://stackoverflow.com/questions/574240/synchronized-block-vs-synchronized-method – dusan Dec 04 '11 at 14:15

1 Answers1

4

The two are identical. See §8.4.3.6 of the Java Language Specification (JLS):

A synchronized method acquires a monitor before it executes. [...] For an instance method, the monitor associated with this (the object for which the method was invoked) is used.

In the example in the JLS, this:

synchronized void bump() { count++; }

is said to have the same effect as this:

void bump() {
    synchronized (this) {
        count++;
    }
}

and your two F methods are very similar to the example bump methods.

Richard Fearn
  • 25,073
  • 7
  • 56
  • 55