使AtomicXXX对象易变

时间:2011-11-11 09:39:32

标签: java concurrency atomicity

我已经阅读了一些关于volatile变量及其AtomicXXX对应物的信息(例如AtomicBoolean)。

但是在某种情况下我需要让AtomicXXX对象本身变得不稳定,还是从来没有必要?

2 个答案:

答案 0 :(得分:1)

阅读this以获取有关何时使用volatile的一些提示和说明。但基本上如果你使用AtomicXXX,你不需要使用volatile。

答案 1 :(得分:1)

你不需要 - 事实上,原子对象应该真的设置为final !!

示例:

private final AtomicInteger atomicInt = new AtomicInteger(0);

private volatile int volatileInt = 0;

public void doStuff() {
  // To use the atomic int, you use the setters and getters!
  int gotAnInt = atomicInt.getAndIncrement();

  // To use a volatile, access and set it directly. 
  int gotAnotherInt = volatileInt;
  volatileInt = someOtherInt;
}
相关问题