简体   繁体   中英

How to make method thread-safe

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM