检查AtomicBoolean并执行某些操作的最安全的方法是什么?

时间:2016-11-18 10:38:28

标签: java multithreading thread-safety atomic atomicity

有没有办法让这个操作像一个操作(一种自定义原子)?

 if (!isShutdownStarted.get()
            && !QUEUE.contains(request.getUserEmail())) {
        try {
            QUEUE.add(request.getUserEmail());
        } 
 //...
 }

其他帖子中的代码

@Override
public void contextDestroyed(ServletContextEvent servletContextEvent) {
    PaymentClient.isShutdownStarted.set(true);
    while (!PaymentClient.QUEUE.isEmpty());
}

1 个答案:

答案 0 :(得分:0)

You cannot use an AtomicBoolean to make another operation or sequence of operations atomic.

If you need to make an intrinsically non-atomic operation or sequence atomic, you need to use locking; e.g. a primitive mutex, a Lock or something equivalent.