Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Thread safety in String class

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?

like image 259
user1766169 Avatar asked May 08 '15 09:05

user1766169


People also ask

What does it mean to say that a class is thread-safe?

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.

How a class is thread-safe?

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.


1 Answers

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.

like image 50
Jon Skeet Avatar answered Oct 27 '22 03:10

Jon Skeet