0

I understand that static method does not guarantee thread safety. Because even though there is a single class method in the entire application, that method can be called simultaneously and could cause thread safety issues if you are not careful. But what happens when that class method doesn't affect any global variable? Is is still Thread Safe? For example, I have this code:

public static String convertToString(int i) {
    return String.valueOf(i);
}

If 2 or more threads were to call this method simultaneously, is it thread safe?

Faraz
  • 6,025
  • 5
  • 31
  • 88
  • "*If 2 or more threads were to call this method simultaneously, is it thread safe?*" - Yes. – Turing85 Aug 21 '19 at 23:07
  • this has a question and answer already: https://stackoverflow.com/questions/13910976/how-to-ensure-thread-safety-of-utility-static-method#targetText=It%20is%20well%20known%20that,and%20mutable%20objects%20are%20not.&targetText=But%20that's%20a%20different%20matter,operates%20only%20on%20its%20arguments. – stringy05 Aug 21 '19 at 23:09
  • There's no shared state, so yes. – shmosel Aug 21 '19 at 23:09
  • 1
    Thank you for sharing that link. It gave a clear and concise answer. Thank you. – Faraz Aug 21 '19 at 23:16

3 Answers3

3

Yes, that method is thread-safe. The issue with thread-safety occurs is when the static method tries to do something more complex, like sharing data.

Going in more detail,

public static String convertToString(int i) {
    return String.valueOf(i);
}

the above method operates only on the parameter i, which resides on the stack. Stack is local to the thread, so it is perfectly thread-safe.

Aiyuni
  • 780
  • 5
  • 15
3

Yes it is thread safe. As long as static method above does not read/modify shared mutable reference or value. For example:-

private static int counter = 0;

public static String convertToString(int i) {

    //this has race conditions.
    counter++;

    return String.valueOf(i);
}
Awan Biru
  • 373
  • 2
  • 10
2

Basically you need synchronization when you are performing non atomic operations like incrementing variable (i++) - update it's value, then read etc.

Such operation like reading value (be careful with double and long) is an atomic operation by definition so it's thread-safe

m.antkowicz
  • 13,268
  • 18
  • 37
  • Your wording on this part is a little bit ambiguous. One could read it as: "`i++` is an atomic operation". – Turing85 Aug 21 '19 at 23:10