Java syncrhonized static methods

If I have such a method

public synchronized static foo()
{

}

it compiles fine.

So this leads me to two questions.

  • What is sync? Class or something else?
  • Can you synchronize a class, does it block the entire object of this class.

for example you could do it

synchronized(Foo) // where Foo is a class
{
}
+3
source share
4 answers

The synchronized static method in MyClassessentially coincides with the block synchronized(MyClass.class). The second example should be rewritten as

synchronized(Foo.class) {
}

to be true.

, , . , synchronized , .

" ", , synchronized, synchronized, synchronized , .

+3

, Class. Class. (Foo.class) getClass() Foo.

( , ): http://docs.oracle.com/javase/tutorial/essential/concurrency/locksync.html

+3
  • class, MyClass.class
  • ,
+2

.

Java 8.4.3.6, "synchronized Methods" :

The synchronized method receives the monitor (ยง17.1) before executing it. For a class (static) method, the monitor associated with the class object for the method class is used. For the instance method, the associated monitor (the object for which the method was called) is used.

0
source

All Articles