Hazelcast - IAtomicLong



Java 中的 Atomic Long 資料結構提供了一種執行緒安全的方式來使用 Long。

類似地,IAtomicLong 更像是一個 AtomicLong 的分散式版本。它提供了類似的功能,其中以下一些是有用的:set、get、getAndSet、incrementAndGet。這裡需要注意的一點是,由於資料結構分佈在多臺機器上,以上函式的效能可能並不相同。

AtomicLong 只有一個同步備份,這意味著如果我們的設定中執行著 5 個 JVM,那麼只有兩個 JVM 會儲存此變數。

讓我們來看一些有用的函式。

初始化並將值設定為 IAtomicLong

示例

public class Application {
   public static void main(String... args) throws IOException {
      //initialize hazelcast instance and the counter variable
      Hazelcast – Data Structures
      HazelcastInstance hazelcast = Hazelcast.newHazelcastInstance();
      IAtomicLong counter = hazelcast.getAtomicLong("counter");
      System.out.println(counter.get());
      counter.set(2);
      System.out.println(counter.get());
      System.exit(0);
   }
}

輸出

執行上述程式碼時,將產生以下輸出

0
2

跨 JVM 的同步

Atomic Long 提供跨 JVM 的併發控制。因此,incrementAndGet、compareAndSet 等方法可以用來原子地更新計數器。

示例

讓我們在兩個 JVM 上同時執行下面的程式碼

public class AtomicLong2 {
   public static void main(String... args) throws IOException,
   InterruptedException {
      // initialize hazelcast instance
      HazelcastInstance hazelcast = Hazelcast.newHazelcastInstance();
      IAtomicLong counter = hazelcast.getAtomicLong("counter");
      for(int i = 0; i < 1000; i++) {
         counter.incrementAndGet();
      }
      System.exit(0);
   }
}

輸出

上述程式碼輸出的第二行將始終為:

2000

如果 incrementAndGet() 不是執行緒安全的,上述程式碼可能不會始終輸出 2000。它可能小於 2000,因為一個執行緒的寫入可能被另一個執行緒覆蓋。

常用方法

序號 函式名稱 & 描述
1

get()

返回當前值

2

set(long newValue)

將值設定為 newValue

3

addAndGet(long value)

原子地新增值並返回更新後的值

4

decrementAndGet(long value)

原子地減去值並返回更新後的值

5

getAndAdd(long value)

原子地返回當前值並存儲當前值和值的和

6

getAndDecrement(long value)

原子地返回當前值並存儲當前值減去值的結果

7

compareAndSet(long expected,long newValue)

如果 oldValue 等於 expected 值,則原子地將值設定為 newValue

8

decrementAndGet(long value)

原子地減去值並返回更新後的值

廣告
© . All rights reserved.