开发者

Do we need to make static methods as synchronized if it is called within synchronized non static method?

开发者 https://www.devze.com 2023-01-29 09:36 出处:网络
My doubt is do we need to make static methods as synchronized if it is called within synchonized non static method?

My doubt is do we need to make static methods as synchronized if it is called within synchonized non static method?

for e.g.

class Test
{

      public static void m2()
      {


      }

      public synchronized void m1()
      {

            Test.m2();
             ----
            ----
      }  

In above case do I need to make m2 as synchronized in order to avoid race condition or should I ke开发者_StackOverflow社区ep it as it is.

}


It depends on what your static method is doing. Do you really need it to be synchronized at all? Is it accessing shared mutable state?

If so, you probably do need to synchronize (although I wouldn't do so just with the synchronized modifier - I'd create a private static final variable with an object to lock on.)

The fact that your instance method is synchronized means that no two threads will be executing it with the same target object - but two threads could both be executing m1 with different target objects, so m2 could be called twice at the same time. Whether that's a problem or not depends on what it's doing. If it's not using any shared state (e.g. it's really just computing something based on its parameters) then it doesn't need to be synchronized at all.

Generally speaking, it's more important for static methods to be thread-safe than instance methods: I typically don't make types themselves thread-safe, but instead try to use a few classes to manage concurrency, with each thread using its own set of separate objects as far as possible.


You do need to make m2 synchronized. Otherwise someone can call that method at the same time. I am assuming m2 would be considered for being synchronized, otherwise it is a moot point.


generally it could be usefull to synchronize a static method. For example in this case:

private static final List<Object> GLOBAL_STATE = new ArrayList<Object>();

public static synchronized void add(Object foo) {
    GLOBAL_STATE.add(foo);
}

But in your case you call the method from another already synchronized method. So you don't have to synchronize it. But in your example you make your static method public. If this was intended, make it synchronized too.

0

精彩评论

暂无评论...
验证码 换一张
取 消