扁豆小虾米 發表於 2026-2-13 23:42:00

6、(InputStream的源码、FilterInputStream源码、BufferedInputStream的源码解读前言)AtomicReferenceFieldUpdater.class和System.arraycopy()函数的用法

<h4 id="一atomicreferencefieldupdater的用法">一、AtomicReferenceFieldUpdater的用法</h4>
<p>  AtomicReferenceFieldUpdater是一个抽象的工具类,其底层是通过反射找到目标字段的内存偏移量,然后利用Unsafe.class提供的CAS(Compare-And-Swap)操作来原子地更新某个类中指定变量的值。如下所示:</p>
<pre><code>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;
   }

   private static final
   AtomicReferenceFieldUpdater&lt;TestAtomicReferenceFieldUpdater, byte[]&gt; 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;
      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();
   }
}
</code></pre>
<p>以上代码执行结果如下:<br>
<img src="https://img2024.cnblogs.com/blog/2485827/202602/2485827-20260213233904007-837491549.png"></p>
<h4 id="二systemarraycopy的用法">二、System.arraycopy的用法</h4>
<p>  该函数共有5个入参,分别如下:<br>
①、Object src:源数组;<br>
②、int srcPos:源数组的起始索引位置;<br>
③、Object dest:目标数组;<br>
④、int destPos:目标数组的起始索引位置;<br>
⑤、int length:需要从源数组中复制的元素个数;<br>
该函数的执行过程如下:<br>
  将源数组中srcPos索引位置~ (srcPos + length - 1)索引位置的元素复制到目标数组的destPos 索引位置~(destPos + length - 1)的索引位置,如果源数组和目标数组是同一个数组对象,则复制操作会先将srcPos索引位置~ (srcPos + length - 1)索引位置的元素复制到一个长度为 length的临时数组中,然后再将临时数组的内容复制到该数组(同一个数组)的destPos 索引位置~(destPos + length - 1)的索引位置。如下所示:</p>
<pre><code>package com.xxx.StreamAndReader;
public class TestSystemArrayCopy {
   public static void main(String[] args) {
      int[] src = new int;
      for (int i = 1; i &lt; 11; i++) {
         src = i;
      }
      int[] dest = new int;
      System.arraycopy(src, 0, dest, 5, 5);
      for (int i = 0; i &lt; dest.length; i++) {
         System.out.println("dest数组的第"+i+"个索引位置的元素是:"+dest);
      }
   }
}
</code></pre>
<p>以上代码执行结果如下:<br>
<img src="https://img2024.cnblogs.com/blog/2485827/202602/2485827-20260213234002163-1583606087.png"></p><br><br>
来源:https://www.cnblogs.com/Carey-ccl/p/19613840
頁: [1]
查看完整版本: 6、(InputStream的源码、FilterInputStream源码、BufferedInputStream的源码解读前言)AtomicReferenceFieldUpdater.class和System.arraycopy()函数的用法