简体   繁体   中英

AtomicBoolean guard for not thread-safe data (volatile piggybacking)

Is it safe to use AtomicBoolean as non-blocking lock for read and write access to not thread-safe data from multiple threads, using construction:

if (lock.compareAndSet(false, true)) {
  try {
    //Access non-volatile fields, non-atomic arrays and not thread-safe classes
  } finally {
    lock.set(false);
  }
} else {
  //Access denied, try again later or right now
}

The data is not accessible outside this construction. I'm almost sure it's safe because of volatile piggybacking effect. Am I right?

The high-level consideration must be whether it safely precludes concurrent access to the critical ressource. This works as AtomicBoolean provides the necessary guarantees. As a rule of thump, the JMM is designed in a way that if you implement the high-level logic correctly, the low level things will be too.

Going more into detail as you do in your question, the volatile reads and writes preclude unintended re-ordering just as you expect (aka “piggybacking”).

You are basically doing what a Lock does too. A ReentrantLock will use an int rather than a boolean , and the Lock s provide a waiting queue which a simple atomic variable does not.

The AbstractQueuedSynchronizer shows how that logic (similar to yours) is implemented around one atomic int variable.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM