Is it thread safe to build strings from local variables using the String
class like in the methods below? Suppose that the methods below are called from several threads.
public static string WriteResult(int value, string name)
{
return string.Format("Result: value={0} name={1}", value, name);
}
public static string WriteResult2(int value, string name)
{
return "Result: value=" + value + " name=" + name;
}
Or do I need to use StringBuilder
to ensure thread safety?
Thread safety is a computer programming concept applicable to multi-threaded code. Thread-safe code only manipulates shared data structures in a manner that ensures that all threads behave properly and fulfill their design specifications without unintended interaction.
A thread-safe class is a class that guarantees the internal state of the class as well as returned values from methods, are correct while invoked concurrently from multiple threads. The collection classes that are thread-safe in Java are Stack, Vector, Properties, Hashtable, etc.
That's absolutely fine. There is no shared state in either piece of code other than the string literals. As strings are immutable, it's fine for strings to be shared freely between threads, and both string.Format
and string.Concat
(implicitly called in the second piece of code) are thread-safe.
Even if one of the parameters were mutable and even if the method mutated the parameters, e.g.
public static void AddResult(int value, List<string> results)
{
results.Add("Value " + value);
}
... then the method itself would still be thread-safe, so long as multiple threads didn't refer to the same List<string>
. If multiple threads did refer to the same List<string>
then it would be unsafe even if it just read from the list, as another thread could be mutating it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With