Is making a defensive copy of the fileName argument necessary in this example?

public static Context getInstanceFromFile(final String fileName) 
throws IOException, FileNotFoundException, ContextException {
    if (fileName == null) {
        throw new NullPointerException("The fileName argument is null.");
    }
    return instance.loadParametersFromFile(String.valueOf(fileName));
}

In theory, another thread can modify the fileName before the loadParametersFromFile method is called. Is the same not true before String.valueOf(fileName) is called?

How can I ensure the value passed in fileName is still the same when loadParametersFromFile is called?

有帮助吗?

解决方案

In Java, Strings are immutable and there's no way for another thread to modify the value of your fileName reference (since it's local to the calling method), so a defensive copy brings absolutely no benefit here.

In general, defensive copies can help to avoid such scenarios, provided there are done at the right time (when no other thread can modify the instance while the copy is running). A better idea for defense, as illustrated by this very String example, is to make passed classes immutable.

其他提示

No, in Java, Strings are immutable (unless you are hacking it with reflection). There is no need to safe-copy it.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top