简体   繁体   English

非同步 static 方法和线程安全

[英]Non-synchronized static methods & thread safety

Let say I have the following method, is the method thread safe?假设我有以下方法,该方法线程安全吗?

public static void forwardProcessingPerStudy(String str)
{
        someNonStaticMethodProcessingOnObj(str);
}

Ie: Could two separate threads run the above method at the same time passing different instance of str ( say two completely different string objects ) and conflict with each other?即:两个单独的线程是否可以同时运行上述方法并传递不同的 str 实例(比如两个完全不同的字符串对象)并相互冲突?

For the method to be safe for thread use do I have to make it a synchronized method?为了使该方法对线程使用安全,我是否必须使其成为同步方法?

Yes, two different threads could both run that method at the same time, with either the same string reference or a different one.是的,两个不同的线程可以同时运行该方法,使用相同的字符串引用或不同的引用。

As to whether you need to synchronize, that entirely depends on what someNonStaticMethodProcessingOnObj does.至于是否需要同步,这完全取决于someNonStaticMethodProcessingOnObj做了什么。 The name implies it's calling a non-static method, but given that you don't specify an instance on which to call it, that seems unlikely.该名称暗示它正在调用非静态方法,但鉴于您没有指定要调用它的实例,这似乎不太可能。

If the body of the method (and any methods that are called) doesn't do anything with any shared state, you don't need to worry.如果方法体(以及任何被调用的方法)没有对任何共享的 state 做任何事情,您不必担心。 If it does, you need to think more carefully.如果是这样,您需要更仔细地考虑。

Yes.是的。

No.不。

But the answers with method someNonStaticMethodProcessingOnObj could be different.但是方法someNonStaticMethodProcessingOnObj的答案可能会有所不同。

The method shown is threadsafe, since it doesn't access any stateful information on any object.所示方法是线程安全的,因为它不访问任何 object 上的任何状态信息。

That being said, we have no idea if someNonStaticMethdoProcessingOnObj() is or not, not to mention that the name implies it is non static but it isn't run against any instance.话虽如此,我们不知道 someNonStaticMethdoProcessingOnObj() 是否存在,更不用说名称暗示它不是 static 但它没有针对任何实例运行。

Here's an answer to a similar question where I added some examples that might make this clear for you: difference between synchronizing a static method and a non static method这是一个类似问题的答案,我在其中添加了一些示例,可能会让您清楚这一点: 同步 static 方法和非 static 方法之间的区别

The thing is that adding synchronized to the outer method might not help, as that synchronizes on the associated Class object.问题是向外部方法添加同步可能无济于事,因为这会在关联的 Class object 上同步。 The inner method might need to be synchronized on something else.内部方法可能需要在其他东西上同步。 So some care is needed.所以需要一些照顾。

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

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