Is it safe according to the java memory model to be able to pass a String
between two threads.
In it's simplest is the following always safe:
public static void main(String[] args) throws Exception {
String arg0 = args[0];
CompletableFuture<Void> future = CompletableFuture.runAsync(() -> System.out.println(arg0));
future.get();
}
or something like:
public CompletableFuture<String> reallyNotAGoodImplementation(String arg1, String arg2) throws Exception {
return CompletableFuture.supplyAsync(() -> arg1 + "," + arg2);
}
Before yesterday I would have been unequivocal in saying that is definitely safe as String
is a nice immutable object etc, but I some cause to believe that this might not be safe all the time.
I have some rare exceptions from a running application that indicate that the once in running in the new thread the Strings
appear to be invalid, ie have a null value
char array.
said exception:
java.lang.NullPointerException
at java.lang.String.length(String.java:623)
Caused by: java.lang.NullPointerException
at java.lang.String.getBytes(String.java:941)
Note that they are NPE's from inside String.length()
and String.getBytes()
(java 1.8.0_77)