简体   繁体   中英

Do we need to make static methods as synchronized if it is called within synchronized 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 eg

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 keep 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 (eg 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.

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