Reputation: 27536
Let's say I have following method
public static String addStringItems(String[] items, boolean forceUpperCase) {
StringBuilder builder = new StringBuilder(items.length);
for (String item : items) {
builder.append(item);
}
return forceUpperCase ? builder.toString().toUpperCase() : builder.toString();
}
Now, how do I make it thread-safe, is marking it synchronized
enough?Or should I use StringBuffer
instead of StringBuilder
?Do you have any other suggestions?
Upvotes: 3
Views: 2262
Reputation: 200296
Your method is well-written and as thread-safe as it can be. It accesses no shared state and is basically a pure function. The method is passed an array, which is itself a non-threadsafe object, however that concern should not be taken into consideration when assessing the method's own thread safety.
The key thing to note is that if the caller didn't take care of the thread-safety issues with the String[]
, then there is nothing that this method can do about it, even if it tries to make a defensive copy within a synchronized
block. There is no guarantee that the lock used by this method would be used to protect the String[]
at all other places where it may be modified. This is why the concurrent consistency of the String[]
argument is fundamentally the caller's responsibility.
By the same token, there is no need to use a StringBuffer
, which only makes sense when shared between threads. Your StringBuilder
never leaves the method and the method is executed on the same thread in its entirety.
Upvotes: 8