Is safe publishing of final instance variables transitive for non-final secondary references?

I know that final variable instances are published safely for all threads after the constructor completes. However, I am wondering if this is still safe if the final instance variable contains a reference to an object containing a non-final instance variable. This secondary, non-final instance variable never changes after the constructor completes. Consider the following example:

public class NonFinalImmutable {
    private Iterable<String> list = Collections.unmodifiableList(Arrays
            .asList("foo", "bar", "foobar"));

    public Iterable<String> getList() {
        return list;
    }
}

public class FinalImmutable {
    private final NonFinalImmutable reference;
    private final String[] array;

    public FinalImmutable(NonFinalImmutable reference,
            String... arrayEntries) {
        this.reference = reference;
        this.array = arrayEntries;
    }

    public NonFinalImmutable getReference() {
        return reference;
    }

    public String[] getArray() {
        return array;
    }
}

private void execute() {
    new Thread() {
        @Override
        public void run() {
            useLater(construct());
        }
    }.start();
}

private FinalImmutable construct() {
    return new FinalImmutable(new NonFinalImmutable(), "asdf", "jklö");
}

private void useLater(FinalImmutable finalImmutable) {
    new Thread() {
        @Override
        public void run() {
            for (String s : finalImmutable.getReference().getList()) {
                System.out.println(s);
            }
            System.out.println();
            for (String s : finalImmutable.getArray()) {
                System.out.println(s);
            }
        }
    }.start();
}

Can I use the contents of copies of the variables FinalImmutable.reference, and FinalImmutable.arrayin another thread, even if they do not contain the final instance variables?

+4
1

, , . , . 2014

. , w , r2 . , , , F, a r1, , r2 w.

,

, , , , , r2.

, NonFinalImmutable, . NonFinalImmutable , .

+3

Source: https://habr.com/ru/post/1620621/


All Articles