- iOS/Objective-C 元类和类别
- objective-c - -1001 错误,当 NSURLSession 通过 httpproxy 和/etc/hosts
- java - 使用网络类获取 url 地址
- ios - 推送通知中不播放声音
在阅读 Java 中 java.util.Random 类的文档时,我偶然发现了 next
方法中的一些东西,我无法完全理解。
protected int next(int bits) {
long oldseed, nextseed;
AtomicLong seed = this.seed;
do {
oldseed = seed.get();
nextseed = (oldseed * multiplier + addend) & mask;
} while (!seed.compareAndSet(oldseed, nextseed));
return (int)(nextseed >>> (48 - bits));
}
我注意到 !seed.compareAndSet(oldseed, nextseed)
的使用,我想了解它的用途。什么解释?
最佳答案
来自 JavaDoc for compareAndSet :
Atomically sets the value to the given updated value if the current value == the expected value.
这样做是为了确保在 seed.get()
和集合(在 comapreAndSet 内)之间,没有其他线程调用另一个 set()
(例如,通过并行调用 next()
)。因为旧的种子是用来计算下一个种子的。如果在其他线程之间调用了 seed.set()
方法,则不会使用最新值计算“下一个”种子。将使用最后一个值之前的值,并且该算法在多线程环境中会产生副作用。
该算法用于线程保存。因为如果旧值不是预期值,将重复循环直到两个值匹配。
关于java - 为什么 Random 中的 next 方法使用 compareAndSet?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33350061/
Java 通过其原子类公开 CAS 操作,例如 boolean compareAndSet(expected,update) JavaDocs指定 compareAndSet 操作的内存效果如下: c
假设您有以下类(class) public class AccessStatistics { private final int noPages, noErrors; public Acces
正在学习并发编程类(class)。 举个例子 final class Counter { private AtomicInteger value; public lon
我想知道原子类中 set() 和 compareAndSet() 的区别。 set() 方法是否也保证了原子过程?例如这段代码: public class sampleAtomic{ priv
今天我在采访中被问到下一个问题:“如果您在处理器不支持 CAS 操作的机器上调用 AtomicLong 的 compareAndSet 方法,会发生什么情况”。 能否请您帮我解决这个问题,并在可能的情
我正在实现一个简单的缓存,并将缓存存储为 AtomicReference。 private AtomicReference> cacheData; 应该从数据库表中(延迟地)填充缓存对象。 我提供了一
我正在试验 java.util.concurrent 并试图找出如何正确使用 AtomicReference.compareAndSet 来管理对单个共享状态单元的并发访问。 特别是:compareA
spring-data-redis 模块包含 RedisAtomicLong 类。 在这个类中你可以看到 public boolean compareAndSet(long expect, long
From the Java AtomicReferenceFieldUpdater docs : Note that the guarantees of the compareAndSet metho
源码是一样的。 public final boolean compareAndSet(V expect, V update) { return unsafe.compareAndSwapObj
在阅读 Java 中 java.util.Random 类的文档时,我偶然发现了 next 方法中的一些东西,我无法完全理解。 protected int next(int bits) { l
Java 的 AtomicInteger 提供 public final boolean compareAndSet(int expect, int update) .如果返回false,我想知道比较
线程标题应该是不言自明的......我对 AtomicBoolean 类的以下方法的规范有点困惑: java.util.concurrent.atomic.AtomicBoolean#compareA
我希望将 AtomicLong 中的当前 timestamp 与 currentTimeMS 进行比较,以便我知道是否已经过去了一段时间,如果是,则只有一个单线程将进入一个代码块,但据我所知,comp
来自AtomicLong的源代码: public final boolean compareAndSet(long expect, long update) { return
因为 Atomic 意味着线程安全。当 .set() 本身在 Java 中是原子和线程安全的时,我们什么时候使用 compareAndSet? 举例来说,我想自动设置一个变量,这样每个其他线程都可以看
static boolean unsynchronizedSetter(Date expected){ Date newDate = new Date(); AtomicReferen
VarHandle 显示以下错误 - Exception in thread "main" java.lang.NoSuchMethodError: VarHandle.compareAndSet(V
我正在实现一个请求实例的 FIFO 队列(为速度而预先分配的请求对象),并开始使用 add 方法上的“同步”关键字。该方法很短(检查固定大小缓冲区中是否有空间,然后将值添加到数组)。使用visualV
我想知道调用之间是否有任何区别(或可能的副作用): AtomicBoolean.set(true) 和 AtomicBoolean.compareAndset(false, true) AtomicB
我是一名优秀的程序员,十分优秀!