2

Possible Duplicate:
How do synchronized static methods work in Java?

Can someone make me understand the fundamental difference between the following two functions:

public static void synchronized f() {… } 

and

public void synchronized f() {… }
Community
  • 1
  • 1
randon
  • 95
  • 3
  • 8
  • The [second answer](http://stackoverflow.com/questions/578904/how-do-synchronized-static-methods-work-in-java/582500#582500) in @Oli's link answers this question directly. – Mark Peters Jun 22 '11 at 17:22

4 Answers4

12

In the case of

public void synchronized f(){...}

The synchronization is per instance of the of enclosing class. This means that multiple threads can call f on different instances of the class.

For

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

Only one thread at a time can call that method, regardless of the number of instances of the enclosing class.

Technically, the monitor taken by synchronized in the first example is the of the object instance and the monitor take in the second example is that of the Class object.

Note that, if you have classes of the same name in different ClassLoaders, the do not share the same monitor, but this is a detail you're unlikely to encounter.

Rob Harrop
  • 3,445
  • 26
  • 26
  • Is there a substitute for "synchronized" in Java, say we have same thread access restriction, without using "synchronized" keyword? – randon Jun 22 '11 at 18:16
  • 1
    You can get the same semantics as `synchronized` by using one of the [`Lock`](http://download.oracle.com/javase/6/docs/api/java/util/concurrent/locks/Lock.html) implementations. – Rob Harrop Jun 22 '11 at 21:31
2

In a "static synchnronized" method, the lock that is synchronized against is on the class itself; in a "synchornized" method, the lock is on the object. Note that this means that a "static synchronzied" method will not be blocked by a running "synchronzied" method, and vice versa. For more info, see: http://geekexplains.blogspot.com/2008/07/synchronization-of-static-and-instance.html

Edward Loper
  • 15,374
  • 7
  • 43
  • 52
1

I think:

public void synchronized f() {… } synchronizes on object itself (this)

public static void synchronized f() {… } synchronizes on Class instance of an object (object.getClass() or SomeClass.getClass)

I can be wrong

Thresh
  • 943
  • 14
  • 23
0

Assuming the method f is in a class Foo. The static version will lock on the the static method call at the class level (the object returned by getClass() or Foo.class). The non static version will lock for particular instances of that class, so lets say:

Foo x = new Foo();
Foo y = new Foo();
// Locks method f of instance x, but NOT for y.
x.f();

In the static instance a call to f() will lock for both versions so only one method call to f would be executing at one time.

Justin Thomas
  • 5,680
  • 3
  • 38
  • 63