Search code examples
javac++concurrencymemory-modeljava-memory-model

JMM and Undesirable use of trylock


Undesirable use of trylock

T1                                   T2
x = 42;                              while (lock.trylock())
lock.lock();                               lock.unlock();
                                     assert(x == 42);

In java and c++ memory model both allow x=42 to move after lock(1). And therefore assert could fail in T2 thread. Therefore in C++ memory model they defined behaviour of trylock being faling could be spurious. But i didn't find what are the specs for trylock in java memory model. Can assert in thread 2 is guaranteed to pass in Java. Reference would help!

Refernce : http://rsim.cs.illinois.edu/Pubs/08PLDI.pdf


Solution

  • From the javadoc for Lock:

    Unsuccessful locking and unlocking operations, and reentrant locking/unlocking operations, do not require any memory synchronization effects.