Synchronized in static methods, and in nonstatic methods

Asked

Viewed 519 times

9

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

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

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

    public synchronized  void test2(){}

}

This would be a Thread-Safe class?

1 answer

5

Is not the even lock, precisely because of the static.

  • Synchronized + Static: will result in a single instance involving the same lock for all who attempt to invoke.

    • Thread 1 calls: Foo.test();
    • Thread 2 calls: Foo.test();, she’ll have to wait for the first finish.


  • Synchronized - Static: will result in a lock for EACH instance of your class Foo, being treated differently.

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


What will guarantee if it is a class Thread-Safe or not, it will depend a lot on your own code and with what you will manipulate, it will be safe when no chances of data being corrupted by high competition. So you don’t necessarily need to have the synchronized depending on the data you are working on.

  • Cool @Maiconcarraro, interesting mechanism. And how would it be if I wanted the lock of the static method to be the same as the non-static method, in other words, how to make both types of method share the mesom synchronization mechanism?

  • You mean the test() function as test2()? I really can’t say, I know the other way around would be possible, but maybe you wanted to play with Reentrantlock

  • 4

    If the method is static, lock is done in the class Foo.class. So just make the dynamic methods have lock in the class as well Foo.class (this is done by placing the method code inside a block synchronized(Foo.class) { ... } instead of declaring the method itself as synchronized).

  • @Piovezan, cool, great solution, really works!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.