23 Kasım 2022 Çarşamba

AtomicLongFieldUpdater Sınıfı

Giriş
Şu satırı dahil ederiz
import java.util.concurrent.atomic.AtomicLongFieldUpdater;
Aslında soyut bir sınıf. Kalıtım şöyle
AtomicLongFieldUpdater 
  CASUpdater
  LockedUpdater

Bu sınıf Neden Lazım
Açıklaması şöyle. Yani performans yüzünden AtomicX yerine volatile X kullanıyoruz.
The class AtomicLongFieldUpdater is one of the three field updater classes. The field updater classes exist primarily for performance reasons. Instead of using atomic variables, one can use ordinary volatile variables that occasionally need to be get and then set atomically. 
Hangi Durumda Kullanılır
Açıklaması şöyle.
In the case where multi-threaded access is needed, but most operations are simple reads or writes, with only a few atomic operations needed, you can create one static instance of AtomicLongFieldUpdate and use this when atomic updates are needed. The memory/runtime overhead is then similar to a simple volatile variable, except for the atomic operations which are of the order of (or slightly more expensive than) the ordinary AtomicLong operations
Yani read işleminin çokça ancak write işleminin az olduğu bir durum düşünelim. write işlemi birden fazla thread tarafından yapılıyorsa volatile kullanamayız. Ancak AtomicLong'un maliyetini de istemiyoruz. İşte bu durumda AtomicLongFieldUpdater  birden fazla thread tarafından volatile nesnenin atomic olarak güncellenmesini sağlıyor.

Dolayısıyla maliyet şöyle
ordinary long: cheap, but unsafe for multi-threaded access
volatile long: more expensive, safe for multi-threaded access, atomic operations not possible
AtomicLongFieldUpdater : Bu aradaki boşluğu dolduruyor
AtomicLong: most expensive, safe for multi-threaded access, atomic operations possible
Örnek
Şöyle yaparız
public class Foo {

  private static final AtomicLongFieldUpdater<Foo> ENTRY_COUNT = 
    AtomicLongFieldUpdater.newUpdater(Foo.class,"entryCount");

  private volatile long entryCount;

  public void bar() {
    ENTRY_COUNT.incrementAndGet(this);
    ..   
}


Hiç yorum yok:

Yorum Gönder