"is the != check thread safe?" Code Answer


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.

By bobvt on August 31 2022

Answers related to “is the != check thread safe?”

Only authorized users can answer the Search term. Please sign in first, or register a free account.