I recently argued with a friend over code like this:
import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; public class PrivateFieldInEnclosing { private long value; PrivateFieldInEnclosing() {} void execute() { value = initializeValue(); ExecutorService executor = Executors.newCachedThreadPool(); executor.submit(new Y()); } class Y implements Runnable { @Override public void run() { System.out.println(value); } } private long initializeValue() { return 20; } public static void main(String[] args) { new PrivateFieldInEnclosing().execute(); } }
I argued that it is possible that value can be considered as 0 in Y , because there is no guarantee that the assignment value = initializeValue() will be visible in the threads of the executors. I said that it needs to make value mutable field.
He contradicted me and said that since this is a private instance field with the value assigned before the stream was created, then this value is visible.
I looked through https://docs.oracle.com/javase/specs/jls/se7/html/jls-17.html#jls-17.4 , but I could not say what I could use to support my application. Can someone help me? Thanks!
java multithreading concurrency
Marc g
source share