简体   繁体   English

java中long值的原子赋值

[英]Atomic assignment of long value in java

I have the use case to update epoch time of events in a long variable.我有一个用例来更新 long 变量中事件的纪元时间。 This variable will have lots of concurrent reads and writes as well.这个变量也会有很多并发读取和写入。 Here are the requirements in detail:以下是详细要求:

  1. Very fast completion of reads and writes读取和写入的完成速度非常快
  2. Reads may or may not return latest result but should not return corrupted result读取可能会也可能不会返回最新结果,但不应返回损坏的结果
  3. Writes are simple assignment to a new epoch value, no addition, subtraction or calculation is required写入是对新纪元值的简单分配,不需要加法、减法或计算

Which of the alternatives is a better option for my use case:哪种替代方案更适合我的用例:

  1. primitive long with volatile keyword带有 volatile 关键字的原始 long
  2. AtomicLong原子长
  3. LongAccumulator with accumulatorFunction being (x,y) -> y LongAccumulator with accumulatorFunction 是(x,y) -> y
  4. Two different variables - one for only reading values and other a volatile variable just for writing value, the value of write variable one being copied to read variable in some interval两个不同的变量 - 一个仅用于读取值,另一个用于写入值的 volatile 变量,写入变量的值在某个时间间隔内被复制到读取变量

使用AtomicLong因为它有助于避免显式锁定的额外开销

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

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