开发者

Java Static Synchronized [duplicate]

This question already has answers here: Closed 11 years ago.

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() {… } 
开发者_StackOverflow中文版

and

public void synchronized f() {… }


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.


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


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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜