Is the != check thread safe?

后端 未结 8 1845
醉酒成梦
醉酒成梦 2021-01-29 18:56

I know that compound operations such as i++ are not thread safe as they involve multiple operations.

But is checking the reference with itself a t

8条回答
  •  傲寒
    傲寒 (楼主)
    2021-01-29 19:32

    No, it is not. For a compare the Java VM must put the two values to compare on the stack and run the compare instruction (which one depends on the type of "a").

    The Java VM may:

    1. Read "a" two times, put each one on the stack and then and compare the results
    2. Read "a" only one time, put it on the stack, duplicate it ("dup" instruction) and the run the compare
    3. Eliminate the expression completely and replace it with false

    In the 1st case, another thread could modify the value for "a" between the two reads.

    Which strategy is chosen depends on the Java compiler and the Java Runtime (especially the JIT compiler). It may even change during the runtime of your program.

    If you want to make sure how the variable is accessed, you must make it volatile (a so called "half memory barrier") or add a full memory barrier (synchronized). You can also use some hgiher level API (e.g. AtomicInteger as mentioned by Juned Ahasan).

    For details about thread safety, read JSR 133 (Java Memory Model).

提交回复
热议问题