Is the != check thread safe?

后端 未结 8 1844
醉酒成梦
醉酒成梦 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.

    0 讨论(0)
  • 2021-01-29 19:40

    Proved with test-ng:

    public class MyTest {
    
      private static Integer count=1;
    
      @Test(threadPoolSize = 1000, invocationCount=10000)
      public void test(){
        count = new Integer(new Random().nextInt());
        Assert.assertFalse(count != count);
      }
    
    }
    

    I have 2 fails on 10 000 invocations. So NO, it is NOT thread safe

    0 讨论(0)
提交回复
热议问题