使 AtomicXXX 对象变得易失性

发布于 2024-12-15 05:44:15 字数 120 浏览 1 评论 0原文

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

但是,在某些情况下,我需要使 AtomicXXX 对象本身具有易失性,还是根本没有必要?

I have read some info about volatile variables and their AtomicXXX counterparts, (e.g. AtomicBoolean).

But are there situations where I need to make the AtomicXXX object itself volatile, or is it never necessary?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

不打扰别人 2024-12-22 05:44:15

您不需要 - 事实上,原子对象确实应该设置为 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;
}

You don't need to - in fact, the atomic objects should really be set as final!!

Example:

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;
}
岁月无声 2024-12-22 05:44:15

阅读本文,了解何时使用 volatile 的一些提示和说明。但基本上,如果您使用 AtomicXXX,则不需要使用 volatile。

Read this for some tips and explanation when to use volatile. But basically if you are using AtomicXXX you DO NOT NEED to use volatile.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文