One Two Three
One Two Three

Reputation: 23537

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

Upvotes: 4

Views: 115

Answers (3)

rgettman
rgettman

Reputation: 178313

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.

Upvotes: 2

rocketboy
rocketboy

Reputation: 9741

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.

Upvotes: 0

Lokesh
Lokesh

Reputation: 7940

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.

Upvotes: 3

Related Questions