Object publishing and thread safety

I read in Java Concurrency In Practice that publishing objects before they are fully assembled could compromise thread safety. Can someone explain this?

+6
source share
2 answers

Consider this code:

public class World{ public static Point _point; public static void main(String[] args){ new PointMaker().start(); System.out.println(_point); } } public class Point{ private final int _x, _y; public Point(int x, int y){ _x = x; World._point = this;//BAD: publish myself before I'm fully constructed //some long computation here _y = y; } public void toString(){ return _x + "," + _y; } } public class PointMaker extends Thread{ public void run(){ new Point(1, 1); } } 

Because Point published before setting _y , a call to println may give "1,0" instead of the expected "1,1" .

(Note that it can also give "null" if PointMaker + Point.<init> not far enough to set the World._point field before the println call is made.)

+3
source

the new operator is allowed to return the value until the class constructor completes. Thus, the variable may not read null, but contains an uninitialized instance of the class. This is due to byte reordering.

Some clarifications: From the point of view of a single JVM thread, it is allowed to reorder commands. When creating an instance, traditionally you think it looks like this:

  • allocate memory
  • start initialization (constructor)
  • assign a link to var

Although in fact the JVM can do something like:

  • allocate memory
  • assign a link to var
  • start initialization (Constructor)

This has performance advantages, as addresses do not need to be searched again. From the point of view of a single thread, this does not change the order of logic. The program works great. But this creates a problem in multi-threaded code. This means that the link can be published before the constructor starts. To do this, you must follow the "happens sooner" rule to make sure that the instance is fully initialized. Declaring volatile dos variables enforces such rules — up to rules.

More on reordering: http://www.cs.umd.edu/~pugh/java/memoryModel/jsr-133-faq.html#reordering

+1
source

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


All Articles