简体   繁体   中英

synchorised static method vs synchronise class object

Suppose my Foo class looked like this

public class Foo
{
    public static void func_1() { /* do something */ }
    public static void func_2() { /* do something */ }
}

and that my Bar class looked like this

public class Bar
{
    public void method_1()
    {
         synchronized(Foo.class)
         {
             Foo.func_1();
         } 
    }          
}

Now instead of locking Foo.class object in Bar.method_1 , could I have declared Foo.func_1 and Foo.func_2 as synchronized , and still archived the same purpose?

Thank you

A static synchronized method obtains lock on class and by taking lock on Foo.class , you are doing same thing. So yes they will achieve same thing.

Yes, they achieve the same thing -- locking Foo.class . Here's the relevant excerpt from the Java Language Specification, Section 8.4.3.6 :

For a class (static) method, the monitor associated with the Class object for the method's class is used.

Using synchronized on the static func_1() or func_2() methods in your Foo class locks the Foo.class implicitly, while synchronized(Foo.class) locks it explicitly.

Yes they are pretty much the same. The only difference is : in one case lock is acquired before calling the method and in another it is acquired later.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM