gpt4 book ai didi

java - Java 流中的 atomicLong

转载 作者:塔克拉玛干 更新时间:2023-11-02 19:05:23 24 4
gpt4 key购买 nike

我不能递减流中的公共(public)长值(流中使用的外部声明值必须是最终值),所以我必须在 java 流中使用 AtomicLong:

var users = Stream<User> getUsers();
var dec = new AtomicLong(10);
long dec = 10;

// users is a
users.forEach(u->{

// does not work within streams, so I have to use AtomicLong
dec--;

// this works
dec.decrementAndGet();


// which one should I use, if I only want to get the raw value?
long actualValue = dec.getPlain();
long actualValue = dec.get(); // the same as dec.getOpaque();

});

我看不出 dec.getPlain()dec.get() 之间有任何区别。我不明白

with memory semantics of reading

在 API 中描述。这些方法的区别在哪里?

如果我只有一个读取 actualValue 的线程,我应该使用哪个。

最佳答案

区别在于从内存中获取结果的方法。 IE。如果它被读取为好像声明为 volatile 或作为普通变量。 volatile 适用于被多个线程同时访问的变量。当一个线程正在更改普通变量时,其他线程可能永远看不到更改,因为每个线程都可能将变量保存在自己的缓存中。 volatile 变量必须始终从公共(public)内存(而非缓存)读取和写入。这使得同时使用时访问速度变慢但可靠。

当您不并发使用该值时,getPlain() 方法就足够了,而且应该更快。但是将 AtomicLong 用于流的副作用是一种误用,因为以函数式方式编程时,您不应该依赖副作用。

关于java - Java 流中的 atomicLong,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57910793/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com