简体   繁体   English

如果在同步非静态方法中调用静态方法,我们是否需要将其作为同步?

[英]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. 在上面的情况下,我是否需要使m2同步以避免竞争条件或我应该保持原样。

} }

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.) 如果是这样, 可能需要同步(虽然我不只是用做synchronized修改-我想创建一个私有静态final变量与对象锁定)。

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. 实例方法同步这一事实意味着没有两个线程将使用相同的目标对象执行它 - 但是两个线程都可以使用不同的目标对象执行m1 ,因此m2可以同时调用两次。 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. 您需要使m2同步。 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. 我假设m2将被认为是同步的,否则它是一个没有实际意义的点。

generally it could be usefull to synchronize a static method. 通常,它可以用于同步static方法。 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 . 但在您的示例中,您将public static方法。 If this was intended, make it synchronized too. 如果是这样的话,也要synchronized它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM