开发者

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);
}

I.e: 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?

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. 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. If it does, you need to think more carefully.


Yes.

No.

But the answers with method someNonStaticMethodProcessingOnObj could be different.


The method shown is threadsafe, since it doesn't access any stateful information on any 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.


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

The thing is that adding synchronized to the outer method might not help, as that synchronizes on the associated Class object. The inner method might need to be synchronized on something else. So some care is needed.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜