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(); } }
, , Thread#start . : / , Thread#start (, , , ), ( run).
Thread#start
run
, , , ( ), . , , ( Intel, ), , .
, , : n ( , ), Thread1 Holder. Thread2 , . n zero (, , n , zero), !=, Thread1, Holder, n 12, Thread2 ( !=n). .
n
Holder
zero
!=
12
!=n
final , - .
final
Source: https://habr.com/ru/post/1692157/More articles:In the graphic graph of substring R, how to show only one legend? - rGetting large thumbnails from Instagram no longer works with “swap” - phpDoes the application controller have a related template? - ruby | fooobar.comSubmitting backend using devextreme and ui @ react16 stuff - reactjsПочему это никогда не бросает AssertionError даже после его запуска так долго? - javaHow to break .map function - reactjsDifferent definitions of the same lambda - c ++Should I split a SQL Server table? - sqlHow to effectively remove list items in a loop in python - pythonDisable child sizing animation of RecyclerView - androidAll Articles