Synchronized in static methods, and non-static methods

9

If I have a class, where I have two methods one static and one not.

Is the lock the same or not? How to do for the two methods share, the same synchronization mechanism, ie the same lock?

class Foo{
    public synchronized static void test(){}

    public synchronized  void test2(){}

}

Would this be a Thread-Safe class?

    
asked by anonymous 28.06.2015 / 23:11

1 answer

5

It is not the same lock, precisely because of static .

  • synchronized + static : This will result in a single instance implying the same lock for everyone attempting to invoke.

    • Thread 1 calls: Foo.test();
    • Thread 2 calls: Foo.test(); , it will have to wait for the first one to finish.


  • synchronized - static : will result in a lock for EVERY instance of its Foo class being treated differently.

    • Thread 1 calls: foo1.test2();
    • Thread 2 calls: foo1.test2(); , it will have to wait for the first one to finish.
    • Thread 3 calls: foo2.test2(); , it will be executed immediately because it is independent of the other instance.


What will guarantee if it is a Thread-Safe class or not, will depend a lot on your own code and what you will handle, it will be safe when there is no chance the data will be corrupted by high competition. So you do not necessarily have to synchronized depending on the data you are working on.

    
29.06.2015 / 00:09