My code contains some AtomicBoolean fields. Only the get() and set() methods of these fields are called.

我的代码包含一些AtomicBoolean字段。只调用这些字段的get()和set()方法。

Can the types of these fields safely be replaced by primitive boolean?

这些字段的类型可以安全地用原始布尔值替换吗?

I mean, assignment and access operations of primitive booleans are atomic operations in Java. And from that point of view I cannot see any reason to use AtomicBoolean in my case.

我的意思是,原始布尔值的赋值和访问操作是Java中的原子操作。从这个角度来看,我看不出有任何理由在我的案例中使用AtomicBoolean。

In my understanding AtomicBoolean would only make sense if methods like compareAndSet are used, that combine a comparison and access. Am I wrong about that? Could you explain why?

在我的理解中,AtomicBoolean只有在使用像compareAndSet这样的方法时才有意义,它结合了比较和访问。我错了吗?你能解释一下原因吗?

3 个解决方案

#1


5

Atomic variables are described as "better volatiles" in Java Concurrency in Practice (see section 15.3). Here is an extract from this book:

原型变量在Java Concurrency in Practice中被描述为“更好的挥发性”(参见15.3节)。以下是本书的摘录:

The atomic variable classes provide a generalization of volatile variables to support atomic conditional read-modify-write operations. AtomicInteger represents an int value, and provides get and set methods with the same memory semantics as reads and writes to a volatile int.

原子变量类提供volatile变量的泛化,以支持原子条件读 - 修改 - 写操作。 AtomicInteger表示一个int值,并为get和set方法提供与读取和写入volatile int相同的内存语义。

Applied to your case this means that if you're using only get() and set() methods of AtomicBoolean, they can be safely replaced with read-writes to volatile boolean.

应用于您的情况,这意味着如果您只使用AtomicBoolean的get()和set()方法,则可以使用对volatile boolean的读写安全地替换它们。

volatile is needed to guarantee that all threads will see up-to-date value of the variable. Back to Java Concurrency in Practice (section 3.1.4):

需要volatile来保证所有线程都能看到变量的最新值。回到实践中的Java并发(第3.1.4节):

When a field is declared volatile, the compiler and runtime are put on notice that this variable is shared and that operations on it should not be reordered with other memory operations. Volatile variables are not cached in registers or in caches where they are hidden from other processors, so a read of a volatile variable always returns the most recent write by any thread.

当一个字段被声明为volatile时,编译器和运行时会注意到该变量是共享的,并且对它的操作不应该与其他内存操作重新排序。易失性变量不会缓存在寄存器或缓存中,而是隐藏在其他处理器中,因此读取volatile变量始终会返回任何线程的最新写入。

更多相关文章

  1. 根据用户的动态字段对链接列表进行排序
  2. 环境变量在cron中看不到
  3. java中的成员变量和局部变量的区别
  4. 如何在另一个类中使用静态类中的变量?
  5. MongoDB中的按组计算的字段
  6. JAVA 静态方法和静态变量和final和※静态import※
  7. Linux(Centos7.X ) 配置Java 环境变量
  8. java通过映射取得方法对一个类的变量进行赋值
  9. JavaScript基础——变量、作用域和内存问题

随机推荐

  1. C# 5.0引入了两个关键字 --async和await
  2. 解决 ASP.NET Core MySql varchar 字符串
  3. 让WebAPI 返回JSON格式的数据实例教程
  4. 分享GTS-800二次开发流程步骤
  5. socket传输protobuf字节流的实例详解
  6. C# 定时器Timer的实例介绍
  7. C# Md5Hash的用法及实例
  8. 用Shape做动画实例代码
  9. httpHelper 从URL获取值的实例代码
  10. 分享PART_Editor的使用实例