博客 / 詳情

返回

6、(InputStream的源碼、FilterInputStream源碼、BufferedInputStream的源碼解讀前言)AtomicReferenceFieldUpdater.class和System.arraycopy()函數的用法

一、AtomicReferenceFieldUpdater的用法

  AtomicReferenceFieldUpdater是一個抽象的工具類,其底層是通過反射找到目標字段的內存偏移量,然後利用Unsafe.class提供的CAS(Compare-And-Swap)操作來原子地更新某個類中指定變量的值。如下所示:

package com.xxx.StreamAndReader;
import java.io.IOException;
import java.util.concurrent.atomic.AtomicReferenceFieldUpdater;

public class TestAtomicReferenceFieldUpdater {
   protected volatile byte buf[];

   public TestAtomicReferenceFieldUpdater() {
      this.buf = new byte[8];
   }

   private static final
   AtomicReferenceFieldUpdater<TestAtomicReferenceFieldUpdater, byte[]> bufUpdater =
         AtomicReferenceFieldUpdater.newUpdater
               (TestAtomicReferenceFieldUpdater.class, byte[].class, "buf");

   private void method() throws IOException {
      byte[] buffer = buf;
      System.out.println("執行AtomicReferenceFieldUpdater.class::compareAndSet()函數前buf的長度:" + buffer.length);
      int nsz = buffer.length * 2;
      byte nbuf[] = new byte[nsz];
      bufUpdater.compareAndSet(this, buffer, nbuf);
      buffer = buf;
      System.out.println("執行AtomicReferenceFieldUpdater.class::compareAndSet()函數後buf的長度:" + buffer.length);
   }

   public static void main(String[] args) throws IOException {
      TestAtomicReferenceFieldUpdater object = new TestAtomicReferenceFieldUpdater();
      object.method();
   }
}

以上代碼執行結果如下:
clipboard

二、System.arraycopy的用法

  該函數共有5個入參,分別如下:
①、Object src:源數組;
②、int srcPos:源數組的起始索引位置;
③、Object dest:目標數組;
④、int destPos:目標數組的起始索引位置;
⑤、int length:需要從源數組中複製的元素個數;
該函數的執行過程如下:
  將源數組中srcPos索引位置~ (srcPos + length - 1)索引位置的元素複製到目標數組的destPos 索引位置~(destPos + length - 1)的索引位置,如果源數組和目標數組是同一個數組對象,則複製操作會先將srcPos索引位置~ (srcPos + length - 1)索引位置的元素複製到一個長度為 length的臨時數組中,然後再將臨時數組的內容複製到該數組(同一個數組)的destPos 索引位置~(destPos + length - 1)的索引位置。如下所示:

package com.xxx.StreamAndReader;
public class TestSystemArrayCopy {
   public static void main(String[] args) {
      int[] src = new int[10];
      for (int i = 1; i < 11; i++) {
         src[i-1] = i;
      }
      int[] dest = new int[10];
      System.arraycopy(src, 0, dest, 5, 5);
      for (int i = 0; i < dest.length; i++) {
         System.out.println("dest數組的第"+i+"個索引位置的元素是:"+dest[i]);
      }
   }
}

以上代碼執行結果如下:
clipboard

user avatar
0 位用戶收藏了這個故事!

發佈 評論

Some HTML is okay.