0

I am aware of instruction reordering but in the following link Will this AssertionError never be thrown in this case? In approved answer there is a line:

first the the publishing the reference is re-ordered with variable n (there is no happens-before, so this is allowed). Thread1 creates an instance of Holder"

I could not understand the line. Could anyone explain this. How this reordering would happen. I am aware thread.start() has happen before relationship.

what i understand about reordering in java is that instructions can be reordered if they do not have happen before relationship.

int c=0;
int d=1;

can be reordered as

int d=1;
int c=0;

But user explained if thread.starts() would not have happen before relationship then publishing the reference might get reordered with variable n(It is allowed). I couldn't understand how. Reference is in other class and variable n is in different class.

GhostCat
  • 137,827
  • 25
  • 176
  • 248
sdindiver
  • 491
  • 1
  • 5
  • 19
  • 1
    I will take care of formatting further. Thanks – sdindiver Mar 19 '18 at 16:32
  • @Ivan Problem is that i am not able to imagine how code will look like after instruction reordering. I am assuming sequential instructions can be reordered. Can you post a snippet how it might get looked like after instruction reorder? That would help. – sdindiver Mar 19 '18 at 17:00

1 Answers1

0

It could happen if there is no happens-before and if reference to t.holder is set before Holder object is fully initialized. In this case we could have one thread executing

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

And another one executing

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

Second thread reads value of n twice so if we are lucky (or unlucky) the first thread will execute assignment in constructor before those two reads and exception will be thrown.

Ivan
  • 8,508
  • 2
  • 19
  • 30
  • This thing i have guessed. If it were not happens before. Then before fully constructing object, your threads might have started accessing value of n in case of n!=n. In first access it might read value of n as 0 and in second access, it might be possible till that time object has been initialized and value of n has been set as 42. So error would be thrown out. So Over here what is mean by reordering over here? – sdindiver Mar 19 '18 at 17:30
  • Thanks. Now i understood. – sdindiver Mar 19 '18 at 17:38