Maybe the operator n! = N returns true in a multi-threaded environment

Possible duplicate:
How to simulate the conditions of a race designer? How to demonstrate race conditions around values ​​that are not published correctly?

I got the following code from "java concurrency in practice":

public 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’m just interested in the condition n != n , can this be true under a certain circumstance?

+7
source share
5 answers

I assume that you are asking something similar to these questions:

I assume that the book talks about the possibility of exchanging a link to an object before it is fully built, and the act mentioned is an incorrect publication.

Suppose that n != n broken down into the following steps:

 Access n on the right side of the operand Access n on the left side of the operand Compare values 

Then it follows that it is not difficult to imagine the case when the value of n changes between the first two steps. Now I know what you're thinking, "but n never changes." Actually, this is because the two threads could share access to the Holder instance before the constructor for that instance fully executes.

+2
source

Presumably, the compiler optimizes this, as always false, but if not, then yes, in a multi-threaded environment, it can return true.

Suppose that n on the left is copied to register a. Then the current thread is interrupted, the next thread changes n, then we return to the first thread. Now the right-hand side of n is copied to the register, and then the comparison operation is performed (in two registers).

In this case, they will be different.

EDIT: if you look at the bytecode in the nhantdh comment below, you will see that two loads are performed on n, so an interrupt with a modification between them can cause the expression to be true.

0
source

I think in theory this is possible, since n not volatile . This means that a thread can build a Holder object, but the value set to n will not be displayed for another thread running on a different kernel that causes the comparison operation.

0
source

The value will always be the same.

As long as the variable is a primitive type, the variable is not static and you do not have a setter, you can create as many instances of the class as you want. instances will never use the same "object" / instance in the variable "n".

if you change the value after calling the constructor again, the value may be different, for example, setting or reflection.

0
source

I know this expression from C ++. This may be true if n not a number. See Checking if double (or float) is NaN in C ++

-2
source

All Articles