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

打印 上一主题 下一主题

主题 851|帖子 851|积分 2555

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 这么使用的,用它读写一个文件试试:
  1.     // OKio写文件
  2.     private static void writeFileByOKio() {
  3.         try (Sink sink = Okio.sink(new File(path));
  4.              BufferedSink bufferedSink = Okio.buffer(sink)) {
  5.             bufferedSink.writeUtf8("write" + "\n" + "success!");
  6.         } catch (IOException e) {
  7.             e.printStackTrace();
  8.         }
  9.     }
  10.     //OKio读文件
  11.     private static void readFileByOKio() {
  12.         try (Source source = Okio.source(new File(path));
  13.              BufferedSource bufferedSource = Okio.buffer(source)) {
  14.             for (String line; (line = bufferedSource.readUtf8Line()) != null; ) {
  15.                 System.out.println(line);
  16.             }
  17.         } catch (IOException e) {
  18.             e.printStackTrace();
  19.         }
  20.     }
复制代码
从代码中可以看出,读写文件关键一步要创建出 BufferedSource 或 BufferedSink 对象。有了这两个对象,就可以直接读写文件了。
Okio为我们提供的 BufferedSink 和 BufferedSource 就具有以下基本所有的功能,不需要再串上一系列的装饰类

现在开始好奇Okio是怎么设计成这么好用的?看一下它的类设计:

在Okio读写使用中,比较关键的类有 Source、Sink、BufferedSource、BufferedSink。
Source 和 Sink

Source 和 Sink 是接口,类似传统 IO 的 InputStream 和 OutputStream,具有输入、输出流功能。
Sourec 接口主要用来读取数据,而数据的来源可以是磁盘,网络,内存等。
  1. public interface Source extends Closeable {
  2.   long read(Buffer sink, long byteCount) throws IOException;
  3.   Timeout timeout();
  4.   @Override void close() throws IOException;
  5. }
复制代码
Sink 接口主要用来写入数据。
  1. public interface Sink extends Closeable, Flushable {
  2.   void write(Buffer source, long byteCount) throws IOException;
  3.   @Override void flush() throws IOException;
  4.   Timeout timeout();
  5.   @Override void close() throws IOException;
  6. }
复制代码
BufferedSource 和 BufferedSink

BufferedSource 和 BufferedSink 是对 Source 和 Sink 接口的扩展处理。Okio 将常用方法封装在 BufferedSource/BufferedSink 接口中,把底层字节流直接加工成需要的数据类型,摒弃 Java IO 中各种输入流和输出流的嵌套,并提供了很多方便的 api,比如 readInt()、readString()
  1. public interface BufferedSource extends Source, ReadableByteChannel {
  2.   Buffer getBuffer();
  3.   int readInt() throws IOException;
  4.   String readString(long byteCount, Charset charset) throws IOException;
  5. }
复制代码
  1. public interface BufferedSink extends Sink, WritableByteChannel {
  2.   Buffer buffer();
  3.   BufferedSink writeInt(int i) throws IOException;
  4.   BufferedSink writeString(String string, int beginIndex, int endIndex, Charset charset)
  5.       throws IOException;
  6. }
复制代码
RealBufferedSink 和 RealBufferedSource

上面的 BufferedSource 和 BufferedSink 都还是接口,它们对应的实现类就是 RealBufferedSink 和 RealBufferedSource 了。
  1. final class RealBufferedSource implements BufferedSource {
  2.   public final Buffer buffer = new Buffer();
  3.   
  4.   @Override public String readString(Charset charset) throws IOException {
  5.     if (charset == null) throw new IllegalArgumentException("charset == null");
  6.     buffer.writeAll(source);
  7.     return buffer.readString(charset);
  8.   }
  9.   
  10.   //...
  11. }
复制代码
  1. final class RealBufferedSink implements BufferedSink {
  2.   public final Buffer buffer = new Buffer();
  3.   
  4.   @Override public BufferedSink writeString(String string, int beginIndex, int endIndex,
  5.       Charset charset) throws IOException {
  6.     if (closed) throw new IllegalStateException("closed");
  7.     buffer.writeString(string, beginIndex, endIndex, charset);
  8.     return emitCompleteSegments();
  9.   }
  10.   //...
  11. }
复制代码
RealBufferedSource 和 RealBufferedSink 内部都维护一个 Buffer 对象。里面的实现方法,最终实现都转到 Buffer 对象处理。所以这个 Buffer 类可以说是 Okio 的灵魂所在。下面会详细介绍。
Buffer

Buffer 的好处是以数据块 Segment 从 InputStream 读取数据的,相比单个字节读取来说,效率提高了,是一种空间换时间的策略。
  1. public final class Buffer implements BufferedSource, BufferedSink, Cloneable, ByteChannel {
  2.   Segment head;
  3.   @Override public Buffer getBuffer() {
  4.     return this;
  5.   }
  6.   
  7.   @Override public String readString(long byteCount, Charset charset) throws EOFException {
  8.     checkOffsetAndCount(size, 0, byteCount);
  9.     if (charset == null) throw new IllegalArgumentException("charset == null");
  10.     if (byteCount > Integer.MAX_VALUE) {
  11.       throw new IllegalArgumentException("byteCount > Integer.MAX_VALUE: " + byteCount);
  12.     }
  13.     if (byteCount == 0) return "";
  14.     Segment s = head;
  15.     if (s.pos + byteCount > s.limit) {
  16.       // If the string spans multiple segments, delegate to readBytes().
  17.       return new String(readByteArray(byteCount), charset);
  18.     }
  19.     String result = new String(s.data, s.pos, (int) byteCount, charset);
  20.     s.pos += byteCount;
  21.     size -= byteCount;
  22.     if (s.pos == s.limit) {
  23.       head = s.pop();
  24.       SegmentPool.recycle(s);
  25.     }
  26.     return result;
  27.   }
  28.   //...
  29. }
复制代码
从代码中可以看出,这个 Buffer 是个集大成者,实现了 BufferedSink 和 BufferedSource 的接口,也就是意味着它同时具有读和写的功能。
Buffer 包含了指向第一个和最后一个 Segment 的引用,以及当前读写位置等信息。当进行读写操作时,Buffer 会在 Segment 之间移动,而不需要进行数据的实际拷贝。那 Segment ,又是什么呢?
  1. final class Segment {
  2.   //大小是8kb
  3.   static final int SIZE = 8192;
  4.   //读取数据的起始位置
  5.   int pos;
  6.   //写数据的起始位置
  7.   int limit;
  8.   //后继
  9.   Segment next;
  10.   //前继
  11.   Segment prev;
  12.   
  13.   //将当前的Segment对象从双向链表中移除,并返回链表中的下一个结点作为头结点
  14.   public final @Nullable Segment pop() {
  15.     Segment result = next != this ? next : null;
  16.     prev.next = next;
  17.     next.prev = prev;
  18.     next = null;
  19.     prev = null;
  20.     return result;
  21.   }
  22.   //向链表中当前结点的后面插入一个新的Segment结点对象,并移动next指向新插入的结点
  23.   public final Segment push(Segment segment) {
  24.     segment.prev = this;
  25.     segment.next = next;
  26.     next.prev = segment;
  27.     next = segment;
  28.     return segment;
  29.   }
  30.   //单个Segment空间不足以存储写入的数据时,就会尝试拆分为两个Segment
  31.   public final Segment split(int byteCount) {
  32.    //...
  33.   }
  34.   //合并一些邻近的Segment
  35.   public final void compact() {
  36.      
  37.   }
  38. }
复制代码
从 pop 和 push 方法可以看出 Segment 是一个双向链表的数据结构。一个 Segment 大小是 8kb。正是由于 Segment 使 IO 读写操作能如此高效。
和 Segment 紧密相关的还有一个 `SegmentPoll 。
  1. final class SegmentPool {
  2.   static final long MAX_SIZE = 64 * 1024;
  3.   static @Nullable Segment next;
  4.   
  5.   //当池子里面有空闲的 Segment 就直接复用,否则就创建一个新的 Segment
  6.   static Segment take() {
  7.     synchronized (SegmentPool.class) {
  8.       if (next != null) {
  9.         Segment result = next;
  10.         next = result.next;
  11.         result.next = null;
  12.         byteCount -= Segment.SIZE;
  13.         return result;
  14.       }
  15.     }
  16.     return new Segment(); // Pool is empty. Don't zero-fill while holding a lock.
  17.   }
  18.   //回收 segment 进行复用,提高效率
  19.   static void recycle(Segment segment) {
  20.     if (segment.next != null || segment.prev != null) throw new IllegalArgumentException();
  21.     if (segment.shared) return; // This segment cannot be recycled.
  22.     synchronized (SegmentPool.class) {
  23.       if (byteCount + Segment.SIZE > MAX_SIZE) return; // Pool is full.
  24.       byteCount += Segment.SIZE;
  25.       segment.next = next;
  26.       segment.pos = segment.limit = 0;
  27.       next = segment;
  28.     }
  29.   }
  30. }
复制代码
SegmentPool 是一个缓存 Segment 的池,它有 64kb 大小也就是 8 个 Segment 的长度。既然作为一个池,就和线程池的作用类似,为了复用前面被回收的 Segment。recycle() 方法的作用则是回收一个 Segment 对象。被回收的 Segment 对象将会被插入到 SegmentPool 中的单链表的头部,以便后面继续复用。
SegmentPool 的作用防止已申请的资源被回收,增加资源的重复利用,减少 GC,过于频繁的 GC 是会降低性能的
可以看到 Okio 在内存优化上下了很大的功夫,提升了资源的利用率,从而提升了性能。
总结

不仅如此,Okio还提供其他很有用的功能:
比如提供了一系列的方便工具

  • GZip的透明处理
  • 对数据计算md5、sha1等都提供了支持,对数据校验非常方便



作者:树獭非懒链接:https://juejin.cn/post/6923902848908394510

免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!

本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有账号?立即注册

x
回复

使用道具 举报

0 个回复

正序浏览

快速回复

您需要登录后才可以回帖 登录 or 立即注册

本版积分规则

拉不拉稀肚拉稀

金牌会员
这个人很懒什么都没写!
快速回复 返回顶部 返回列表