Is the != check thread safe?

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

    In the absence of synchronization this code

    Object a;
    
    public boolean test() {
        return a != a;
    }
    

    may produce true. This is the bytecode for test()

        ALOAD 0
        GETFIELD test/Test1.a : Ljava/lang/Object;
        ALOAD 0
        GETFIELD test/Test1.a : Ljava/lang/Object;
        IF_ACMPEQ L1
    ...
    

    as we can see it loads field a to local vars twice, it's a non-atomic operation, if a was changed in between by another thread comparison may produce false.

    Also, memory visibility problem is relevant here, there is no guarantee that changes to a made by another thread will be visible to the current thread.

提交回复
热议问题