Is the != check thread safe?

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.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)