0

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?

james4563
  • 169
  • 1
  • 13

4 Answers4

4

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.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • Thanks, I should have taken more care writing my example, I didn't make it overly clear with the someNonStaticMethodProcessingOnObj() method. I think you have answered what I was asking though, different String objects could conflict/change inside that method if running from different threads. – james4563 Jun 28 '11 at 13:49
  • @James: String is immutable and thread-safe, so different strings wouldn't be a problem - unless they're used to do something else to shared state. – Jon Skeet Jun 28 '11 at 13:50
  • Thanks, that makes perfect sense now. – james4563 Jun 28 '11 at 13:59
0

Yes.

No.

But the answers with method someNonStaticMethodProcessingOnObj could be different.

Istao
  • 7,425
  • 6
  • 32
  • 39
0

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.

Robin
  • 24,062
  • 5
  • 49
  • 58
0

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.

Community
  • 1
  • 1
Daniel Lundmark
  • 2,370
  • 16
  • 11