简体   繁体   English

Java中的原子布尔与同步布尔

[英]Atomic Boolean vs SynchronizedBoolean in Java

I've come across these two in some multi-threaded code and was wondering if there is if/any difference between the two. 我在一些多线程代码遇到这两种,想知道是否存在,如果/两者之间有什么区别。

I mean does the use of an AtomicBoolean, rather than a SynchronizedBoolean, make a significant difference in performance? 我的意思是不使用的的AtomicBoolean的,而不是SynchronizedBoolean,使性能有显著差异?

And does it affect the correctness of the computation? 它会影响计算的正确性吗?

AtomicBoolean is a part of the standard java concurrent package. AtomicBoolean是标准Java并发包的一部分。 SynchronizedBoolean is part of a set of utilities created by Doug Lea (author of much of the java concurrent packages). SynchronizedBoolean是Doug Lea(许多Java并发包的作者)创建的一组实用程序的一部分。 Performance-wise, you should expect AtomicBoolean to perform better -- it uses a volatile boolean whereas SynchronizedBoolean uses a ReadWriteLock. 在性能方面,您应该期望AtomicBoolean性能更好-它使用易失性布尔值,而SynchronizedBoolean使用ReadWriteLock。

However in practice for most applications you won't notice much difference. 但是实际上,对于大多数应用程序,您不会发现太大差异。

The real difference (and what should guide your choice) is in the semantics the two classes offer. 真正的区别(以及应该指导您选择的内容)在于这两个类提供的语义上。 AtomicBoolean provides just simple set/get/compareAndSet operations. AtomicBoolean仅提供简单的set / get / compareAndSet操作。 The SynchronizedBoolean offers atomic boolean operations and exposes its internal lock to allow you to execute Runnables within the context of its value. SynchronizedBoolean提供原子布尔操作,并公开其内部锁,以使您可以在其值的上下文中执行Runnable。

Doug Lea has offered this source free to the community. Doug Lea已免费向社区提供了此资源。 I have found an extension to SynchronizedBoolean, WaitableBoolean particularly useful since it allows you to execute a Runnable within the lock whenever a particular state change occurs. 我发现SynchronizedBoolean, WaitableBoolean的扩展特别有用,因为它允许您在发生特定状态变化时在锁内执行Runnable。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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