【轉】值得一用的 IO 神器 Okio

IO 神器 Okio

官方 是這麼介紹 Okio 的:

Okio is a library that complements java.io and java.nio to make it much easier to access, store, and process your data. It started as a component of OkHttp, the capable HTTP client included in Android. It’s well-exercised and ready to solve new problems.

重點是這一句它使訪問,存儲和處理數據變得更加容易,既然 Okio 是對 java.io 的補充,那是否比傳統 IO 好用呢?

看下 Okio 這麼使用的,用它讀寫一個文件試試:

    // OKio寫文件 
    private static void writeFileByOKio() {
        try (Sink sink = Okio.sink(new File(path));
             BufferedSink bufferedSink = Okio.buffer(sink)) {
            bufferedSink.writeUtf8("write" + "\n" + "success!");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    //OKio讀文件
    private static void readFileByOKio() {
        try (Source source = Okio.source(new File(path));
             BufferedSource bufferedSource = Okio.buffer(source)) {
            for (String line; (line = bufferedSource.readUtf8Line()) != null; ) {
                System.out.println(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

從代碼中可以看出,讀寫文件關鍵一步要創建出 BufferedSourceBufferedSink 對象。有了這兩個對象,就可以直接讀寫文件了。

Okio爲我們提供的 BufferedSink 和 BufferedSource 就具有以下基本所有的功能,不需要再串上一系列的裝飾類

現在開始好奇Okio是怎麼設計成這麼好用的?看一下它的類設計:

在Okio讀寫使用中,比較關鍵的類有 Source、Sink、BufferedSource、BufferedSink。

Source 和 Sink

SourceSink 是接口,類似傳統 IO 的 InputStreamOutputStream,具有輸入、輸出流功能。

Sourec 接口主要用來讀取數據,而數據的來源可以是磁盤,網絡,內存等。

public interface Source extends Closeable {
  long read(Buffer sink, long byteCount) throws IOException;
  Timeout timeout();
  @Override void close() throws IOException;
}

Sink 接口主要用來寫入數據。

public interface Sink extends Closeable, Flushable {
  void write(Buffer source, long byteCount) throws IOException;
  @Override void flush() throws IOException;
  Timeout timeout();
  @Override void close() throws IOException;
}

BufferedSource 和 BufferedSink

BufferedSourceBufferedSink 是對 SourceSink 接口的擴展處理。Okio 將常用方法封裝在 BufferedSource/BufferedSink 接口中,把底層字節流直接加工成需要的數據類型,摒棄 Java IO 中各種輸入流和輸出流的嵌套,並提供了很多方便的 api,比如 readInt()readString()

public interface BufferedSource extends Source, ReadableByteChannel {
  Buffer getBuffer();
  int readInt() throws IOException;
  String readString(long byteCount, Charset charset) throws IOException;
}
public interface BufferedSink extends Sink, WritableByteChannel {
  Buffer buffer();
  BufferedSink writeInt(int i) throws IOException;
  BufferedSink writeString(String string, int beginIndex, int endIndex, Charset charset)
      throws IOException;
}

RealBufferedSink 和 RealBufferedSource

上面的 BufferedSourceBufferedSink 都還是接口,它們對應的實現類就是 RealBufferedSinkRealBufferedSource 了。

final class RealBufferedSource implements BufferedSource {
  public final Buffer buffer = new Buffer();
  
  @Override public String readString(Charset charset) throws IOException {
    if (charset == null) throw new IllegalArgumentException("charset == null");
    buffer.writeAll(source);
    return buffer.readString(charset);
  }
  
  //...
}
final class RealBufferedSink implements BufferedSink {
  public final Buffer buffer = new Buffer();
  
  @Override public BufferedSink writeString(String string, int beginIndex, int endIndex,
      Charset charset) throws IOException {
    if (closed) throw new IllegalStateException("closed");
    buffer.writeString(string, beginIndex, endIndex, charset);
    return emitCompleteSegments();
  }
  //...
}

RealBufferedSourceRealBufferedSink 內部都維護一個 Buffer 對象。裏面的實現方法,最終實現都轉到 Buffer 對象處理。所以這個 Buffer 類可以說是 Okio 的靈魂所在。下面會詳細介紹。

Buffer

Buffer 的好處是以數據塊 SegmentInputStream 讀取數據的,相比單個字節讀取來說,效率提高了,是一種空間換時間的策略。

public final class Buffer implements BufferedSource, BufferedSink, Cloneable, ByteChannel {
  Segment head;
  @Override public Buffer getBuffer() {
    return this;
  }
  
  @Override public String readString(long byteCount, Charset charset) throws EOFException {
    checkOffsetAndCount(size, 0, byteCount);
    if (charset == null) throw new IllegalArgumentException("charset == null");
    if (byteCount > Integer.MAX_VALUE) {
      throw new IllegalArgumentException("byteCount > Integer.MAX_VALUE: " + byteCount);
    }
    if (byteCount == 0) return "";
    Segment s = head;
    if (s.pos + byteCount > s.limit) {
      // If the string spans multiple segments, delegate to readBytes().
      return new String(readByteArray(byteCount), charset);
    }
    String result = new String(s.data, s.pos, (int) byteCount, charset);
    s.pos += byteCount;
    size -= byteCount;
    if (s.pos == s.limit) {
      head = s.pop();
      SegmentPool.recycle(s);
    }
    return result;
  }
  //...
}

從代碼中可以看出,這個 Buffer 是個集大成者,實現了 BufferedSinkBufferedSource 的接口,也就是意味着它同時具有讀和寫的功能。

Buffer 包含了指向第一個和最後一個 Segment 的引用,以及當前讀寫位置等信息。當進行讀寫操作時,Buffer 會在 Segment 之間移動,而不需要進行數據的實際拷貝。那 Segment ,又是什麼呢?

final class Segment {
  //大小是8kb
  static final int SIZE = 8192;
  //讀取數據的起始位置
  int pos;
  //寫數據的起始位置
  int limit;
  //後繼
  Segment next;
  //前繼
  Segment prev;
  
  //將當前的Segment對象從雙向鏈表中移除,並返回鏈表中的下一個結點作爲頭結點
  public final @Nullable Segment pop() {
    Segment result = next != this ? next : null;
    prev.next = next;
    next.prev = prev;
    next = null;
    prev = null;
    return result;
  }
  //向鏈表中當前結點的後面插入一個新的Segment結點對象,並移動next指向新插入的結點
  public final Segment push(Segment segment) {
    segment.prev = this;
    segment.next = next;
    next.prev = segment;
    next = segment;
    return segment;
  }
  //單個Segment空間不足以存儲寫入的數據時,就會嘗試拆分爲兩個Segment
  public final Segment split(int byteCount) {
   //...
  }
  //合併一些鄰近的Segment
  public final void compact() {
     
  }
}

poppush 方法可以看出 Segment 是一個雙向鏈表的數據結構。一個 Segment 大小是 8kb。正是由於 Segment 使 IO 讀寫操作能如此高效。

Segment 緊密相關的還有一個 `SegmentPoll 。

final class SegmentPool {
  static final long MAX_SIZE = 64 * 1024;
  static @Nullable Segment next;
  
  //當池子裏面有空閒的 Segment 就直接複用,否則就創建一個新的 Segment
  static Segment take() {
    synchronized (SegmentPool.class) {
      if (next != null) {
        Segment result = next;
        next = result.next;
        result.next = null;
        byteCount -= Segment.SIZE;
        return result;
      }
    }
    return new Segment(); // Pool is empty. Don't zero-fill while holding a lock.
  }
  //回收 segment 進行復用,提高效率
  static void recycle(Segment segment) {
    if (segment.next != null || segment.prev != null) throw new IllegalArgumentException();
    if (segment.shared) return; // This segment cannot be recycled.
    synchronized (SegmentPool.class) {
      if (byteCount + Segment.SIZE > MAX_SIZE) return; // Pool is full.
      byteCount += Segment.SIZE;
      segment.next = next;
      segment.pos = segment.limit = 0;
      next = segment;
    }
  }
}

SegmentPool 是一個緩存 Segment 的池,它有 64kb 大小也就是 8Segment 的長度。既然作爲一個池,就和線程池的作用類似,爲了複用前面被回收的 Segment。recycle() 方法的作用則是回收一個 Segment 對象。被回收的 Segment 對象將會被插入到 SegmentPool 中的單鏈表的頭部,以便後面繼續複用。

SegmentPool 的作用防止已申請的資源被回收,增加資源的重複利用,減少 GC,過於頻繁的 GC 是會降低性能的

可以看到 Okio 在內存優化上下了很大的功夫,提升了資源的利用率,從而提升了性能。

總結

不僅如此,Okio還提供其他很有用的功能:

比如提供了一系列的方便工具

  • GZip的透明處理
  • 對數據計算md5、sha1等都提供了支持,對數據校驗非常方便



作者:樹獺非懶

鏈接:https://juejin.cn/post/6923902848908394510

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章