<output id="qn6qe"></output>

    1. <output id="qn6qe"><tt id="qn6qe"></tt></output>
    2. <strike id="qn6qe"></strike>

      亚洲 日本 欧洲 欧美 视频,日韩中文字幕有码av,一本一道av中文字幕无码,国产线播放免费人成视频播放,人妻少妇偷人无码视频,日夜啪啪一区二区三区,国产尤物精品自在拍视频首页,久热这里只有精品12

      【轉】值得一用的 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.

      重點是這一句它使訪問,存儲和處理數(shù)據(jù)變得更加容易,既然 Okio 是對 java.io 的補充,那是否比傳統(tǒng) 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();
              }
          }
      

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

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

      現(xiàn)在開始好奇Okio是怎么設計成這么好用的?看一下它的類設計:

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

      Source 和 Sink

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

      Sourec 接口主要用來讀取數(shù)據(jù),而數(shù)據(jù)的來源可以是磁盤,網(wǎng)絡,內(nèi)存等。

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

      Sink 接口主要用來寫入數(shù)據(jù)。

      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 接口中,把底層字節(jié)流直接加工成需要的數(shù)據(jù)類型,摒棄 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 都還是接口,它們對應的實現(xiàn)類就是 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 內(nèi)部都維護一個 Buffer 對象。里面的實現(xiàn)方法,最終實現(xiàn)都轉到 Buffer 對象處理。所以這個 Buffer 類可以說是 Okio 的靈魂所在。下面會詳細介紹。

      Buffer

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

      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 是個集大成者,實現(xiàn)了 BufferedSinkBufferedSource 的接口,也就是意味著它同時具有讀和寫的功能。

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

      final class Segment {
        //大小是8kb
        static final int SIZE = 8192;
        //讀取數(shù)據(jù)的起始位置
        int pos;
        //寫數(shù)據(jù)的起始位置
        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空間不足以存儲寫入的數(shù)據(jù)時,就會嘗試拆分為兩個Segment
        public final Segment split(int byteCount) {
         //...
        }
        //合并一些鄰近的Segment
        public final void compact() {
           
        }
      }
      

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

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

      final class SegmentPool {
        static final long MAX_SIZE = 64 * 1024;
        static @Nullable Segment next;
        
        //當池子里面有空閑的 Segment 就直接復用,否則就創(chuàng)建一個新的 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 中的單鏈表的頭部,以便后面繼續(xù)復用。

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

      可以看到 Okio 在內(nèi)存優(yōu)化上下了很大的功夫,提升了資源的利用率,從而提升了性能。

      總結

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

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

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



      作者:樹獺非懶

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

      posted @ 2023-08-26 17:43  JMCui  閱讀(256)  評論(0)    收藏  舉報
      主站蜘蛛池模板: 亚洲伊人精品久视频国产| 日本中文一区二区三区亚洲| 固安县| 日本无产久久99精品久久| 日产国产一区二区不卡| 国产va免费精品观看| 欧美成人无码a区视频在线观看| 久久这里都是精品一区| 羞羞影院午夜男女爽爽免费视频| 国产精品成人av电影不卡| 国产麻豆精品手机在线观看| 一区二区三区四区精品黄| 国产97人人超碰CAO蜜芽PROM| 无码一区二区三区av在线播放| 亚洲码和欧洲码一二三四| 99中文字幕精品国产| 伊在人间香蕉最新视频| 亚洲综合精品第一页| 久久精品国产久精国产| 丰满的少妇一区二区三区| 91福利视频一区二区| 亚洲色欲在线播放一区二区三区 | 久久国产精品成人免费| 亚洲精品乱码久久久久久蜜桃图片 | 久久精品国产再热青青青| 霍城县| 在线观看免费网页欧美成| 在线观看成人年视频免费| 铅山县| 粉嫩小泬无遮挡久久久久久| 蜜桃在线一区二区三区| 一本一道av中文字幕无码| 麻豆tv入口在线看| 欧美日韩视频综合一区无弹窗| 1024你懂的国产精品| 国产精品一区二区蜜臀av| 国产精品一区在线蜜臀| 中文字幕乱偷无码av先锋蜜桃| 99久久精品费精品国产一区二| 丁香五香天堂网| 亚洲天堂精品一区二区|