Is the != check thread safe?

后端 未结 8 1853
醉酒成梦
醉酒成梦 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:36

    No, a != a is not thread safe. This expression consists of three parts: load a, load a again, and perform !=. It is possible for another thread to gain the intrinsic lock on a's parent and change the value of a in between the 2 load operations.

    Another factor though is whether a is local. If a is local then no other threads should have access to it and therefore should be thread safe.

    void method () {
        int a = 0;
        System.out.println(a != a);
    }
    

    should also always print false.

    Declaring a as volatile would not solve the problem for if a is static or instance. The problem is not that threads have different values of a, but that one thread loads a twice with different values. It may actually make the case less thread-safe.. If a isn't volatile then a may be cached and a change in another thread won't affect the cached value.

提交回复
热议问题