Is this statement not to be thrown in this case?

First from the code, from the JCIP list http://jcip.net/listings/StuffIntoPublic.java and http://jcip.net/listings/Holder.java

public class SafePublication {
    public static void main(String[] args) throws InterruptedException {
//        System.out.println(Thread.currentThread().getName());
        StuffIntoPublic t = new StuffIntoPublic();
        t.initialize();
        while (true) {
            new Thread(() -> { t.holder.assertSanity(); }).start();
        }
    }
}

//@author Brian Goetz and Tim Peierls
class StuffIntoPublic {
    public Holder holder;

    public void initialize() {
//        System.out.println(Thread.currentThread().getName());
        holder = new Holder(42);
    }
}

//@author Brian Goetz and Tim Peierls
class Holder {
    private int n;

    public Holder(int n ) {
        this.n = n;
    }

    public void assertSanity() {
        if (n != n) {
            throw new AssertionError("This statement is false.");
        }
    }
}

I say that AssertionError will never be thrown in this case due to Thread.start () occurring before the guarantee. Both commented System.out.printlns files print the main one, which means that the main thread is the one that spawns all subsequent threads, creating and causing the threads to start in a while (true) loop.

And since this is the thread that Holder created and initialized, all subsequent threads are safe to be a completely visible holder because of what happened before the guarantee. I'm right?

.

, , , AssertionError

 public static void main(String[] args) throws InterruptedException {
        System.out.println(Thread.currentThread().getName());
        StuffIntoPublic t = new StuffIntoPublic();
        new Thread(() -> t.initialize() ).start();
        while (true) {
            new Thread(() -> { t.holder.assertSanity(); }).start();
        }
    }
+3
1

, , Thread#start . : / , Thread#start (, , , ), ( run).

, , , ( ), . , , ( Intel, ), , .

, , : n ( , ), Thread1 Holder. Thread2 , . n zero (, , n , zero), !=, Thread1, Holder, n 12, Thread2 ( !=n). .

final , - .

+1

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


All Articles