上一篇文章(Okio 源码解析(一):数据读取流程)分析了 Okio 数据读取的流程,从中能够看出 Okio 的便捷与高效。Okio 的另一个优势是提供了超时机制,而且分为同步超时与异步超时。本文具体分析这两种超时的实现。java
回顾一下 Okio.source
的代码:node
public static Source source(InputStream in) { // 生成一个 Timeout 对象 return source(in, new Timeout()); } private static Source source(final InputStream in, final Timeout timeout) { if (in == null) throw new IllegalArgumentException("in == null"); if (timeout == null) throw new IllegalArgumentException("timeout == null"); return new Source() { @Override public long read(Buffer sink, long byteCount) throws IOException { if (byteCount < 0) throw new IllegalArgumentException("byteCount < 0: " + byteCount); if (byteCount == 0) return 0; try { // 超时检测 timeout.throwIfReached(); Segment tail = sink.writableSegment(1); int maxToCopy = (int) Math.min(byteCount, Segment.SIZE - tail.limit); int bytesRead = in.read(tail.data, tail.limit, maxToCopy); if (bytesRead == -1) return -1; tail.limit += bytesRead; sink.size += bytesRead; return bytesRead; } catch (AssertionError e) { if (isAndroidGetsocknameError(e)) throw new IOException(e); throw e; } } @Override public void close() throws IOException { in.close(); } @Override public Timeout timeout() { return timeout; } @Override public String toString() { return "source(" + in + ")"; } }; }
在 Source
的构造方法中,传入了一个 Timeout
对象。在下面建立的匿名的 Source
对象的 read
方法中,先调用了 timeout.throwIfReached()
,这里显然是判断是否已经超时,代码以下:segmentfault
public void throwIfReached() throws IOException { if (Thread.interrupted()) { throw new InterruptedIOException("thread interrupted"); } if (hasDeadline && deadlineNanoTime - System.nanoTime() <= 0) { throw new InterruptedIOException("deadline reached"); } }
这里逻辑很简单,若是超时了则抛出异常。在 TimeOut
中有几个变量用于设定超时的时间:异步
private boolean hasDeadline; private long deadlineNanoTime; private long timeoutNanos;
因为 throwIfReached
是在每次读取数据以前调用而且与数据读取在同一个线程,因此若是读取操做阻塞,则没法及时抛出异常。socket
异步超时与同步超时不一样,其开了新的线程用于检测是否超时,下面是 Socket 的例子。ide
Okio 能够接受一个 Socket
对象构建 Source
,代码以下:this
public static Source source(Socket socket) throws IOException { if (socket == null) throw new IllegalArgumentException("socket == null"); AsyncTimeout timeout = timeout(socket); Source source = source(socket.getInputStream(), timeout); // 返回 timeout 封装的 source return timeout.source(source); }
相比于 InputStream
,这里的额外操做是引入了 AsyncTimeout
来封装 socket
。timeout
方法生成一个 AsyncTimeout
对象,看一下代码:线程
private static AsyncTimeout timeout(final Socket socket) { return new AsyncTimeout() { @Override protected IOException newTimeoutException(@Nullable IOException cause) { InterruptedIOException ioe = new SocketTimeoutException("timeout"); if (cause != null) { ioe.initCause(cause); } return ioe; } // 超时后调用 @Override protected void timedOut() { try { socket.close(); } catch (Exception e) { logger.log(Level.WARNING, "Failed to close timed out socket " + socket, e); } catch (AssertionError e) { if (isAndroidGetsocknameError(e)) { logger.log(Level.WARNING, "Failed to close timed out socket " + socket, e); } else { throw e; } } } }; }
上面的代码生成了一个匿名的 AsyncTimeout
,其中有个 timedout
方法,这个方法是在超时的时候被调用,能够看出里面的操做主要是关闭 socket
。有了 AsyncTimeout
以后,调用其 source
方法来封装 socket
的 InputStream
。code
下面具体看看 AsyncTimeout
。对象
AsyncTimeout
继承了 Timeout
,提供了异步的超时机制。每个 AsyncTimeout
对象包装一个 source
,并与其它 AsyncTimeout
组成一个链表,根据超时时间的长短插入。AsyncTimeout
内部会新开一个叫作 WatchDog
的线程,根据超时时间依次处理 AsyncTimout
链表的节点。
下面是 AsyncTimeout
的一些内部变量:
// 链表头结点 static @Nullable AsyncTimeout head; // 此节点是否在队列中 private boolean inQueue; // 链表中下一个节点 private @Nullable AsyncTimeout next;
其中 head
是链表的头结点,next
是下一个节点,inQueue
则标识此 AsyncTimeout
是否处于链表中。
在上面的 Okio.source(Socket socket)
中,最后返回的是 timeout.source(socket)
,下面是其代码:
public final Source source(final Source source) { return new Source() { @Override public long read(Buffer sink, long byteCount) throws IOException { boolean throwOnTimeout = false; // enter enter(); try { long result = source.read(sink, byteCount); throwOnTimeout = true; return result; } catch (IOException e) { throw exit(e); } finally { exit(throwOnTimeout); } } @Override public void close() throws IOException { boolean throwOnTimeout = false; try { source.close(); throwOnTimeout = true; } catch (IOException e) { throw exit(e); } finally { exit(throwOnTimeout); } } @Override public Timeout timeout() { return AsyncTimeout.this; } @Override public String toString() { return "AsyncTimeout.source(" + source + ")"; } }; }
AsyncTimtout#source
依然是返回一个匿名的 Source
对象,只不过是将参数中真正的 source
包装了一下,在 source.read
以前添加了 enter
方法,在 catch
以及 finally
中添加了 exit
方法。enter
和 exit
是重点,其中 enter
中会将当前的 AsyncTimeout
加入链表,具体代码以下:
public final void enter() { if (inQueue) throw new IllegalStateException("Unbalanced enter/exit"); long timeoutNanos = timeoutNanos(); boolean hasDeadline = hasDeadline(); if (timeoutNanos == 0 && !hasDeadline) { return; // No timeout and no deadline? Don't bother with the queue. } inQueue = true; scheduleTimeout(this, timeoutNanos, hasDeadline); } private static synchronized void scheduleTimeout( AsyncTimeout node, long timeoutNanos, boolean hasDeadline) { // 若是链表为空,则新建一个头结点,而且启动 Watchdog线程 if (head == null) { head = new AsyncTimeout(); new Watchdog().start(); } long now = System.nanoTime(); if (timeoutNanos != 0 && hasDeadline) { node.timeoutAt = now + Math.min(timeoutNanos, node.deadlineNanoTime() - now); } else if (timeoutNanos != 0) { node.timeoutAt = now + timeoutNanos; } else if (hasDeadline) { node.timeoutAt = node.deadlineNanoTime(); } else { throw new AssertionError(); } // 按时间将节点插入链表 long remainingNanos = node.remainingNanos(now); for (AsyncTimeout prev = head; true; prev = prev.next) { if (prev.next == null || remainingNanos < prev.next.remainingNanos(now)) { node.next = prev.next; prev.next = node; if (prev == head) { AsyncTimeout.class.notify(); // Wake up the watchdog when inserting at the front. } break; } } }
真正插入链表的操做在 scheduleTimeout
中,若是 head
节点还不存在则新建一个头结点,而且启动 Watchdog
线程。接着就是计算超时时间,而后遍历链表进行插入。若是插入在链表的最前面(head
节点后面的第一个节点),则主动进行唤醒 Watchdog
线程,从这里能够猜到 Watchdog
线程在等待超时的过程当中是调用了 AsyncTimeout.class
的 wait
进入了休眠状态。那么就来看看 WatchDog
线程的实际逻辑:
private static final class Watchdog extends Thread { Watchdog() { super("Okio Watchdog"); setDaemon(true); } public void run() { while (true) { try { AsyncTimeout timedOut; synchronized (AsyncTimeout.class) { timedOut = awaitTimeout(); // Didn't find a node to interrupt. Try again. if (timedOut == null) continue; // The queue is completely empty. Let this thread exit and let another watchdog thread // get created on the next call to scheduleTimeout(). if (timedOut == head) { head = null; return; } } // Close the timed out node. timedOut.timedOut(); } catch (InterruptedException ignored) { } } } }
WatchDog
主要是调用 awaitTimeout()
获取一个已超时的 timeout
,若是不为空而且是 head
节点,说明链表中已经没有其它节点,能够结束线程,不然调用 timedOut.timedOut()
, timeOut()
是一个空方法,由用户实现超时后应该采起的操做。 awaitTimeout
是获取超时节点的方法:
static @Nullable AsyncTimeout awaitTimeout() throws InterruptedException { // Get the next eligible node. AsyncTimeout node = head.next; // 队列为空的话等待有节点进入队列或者达到超时IDLE_TIMEOUT_MILLIS的时间 if (node == null) { long startNanos = System.nanoTime(); AsyncTimeout.class.wait(IDLE_TIMEOUT_MILLIS); return head.next == null && (System.nanoTime() - startNanos) >= IDLE_TIMEOUT_NANOS ? head // The idle timeout elapsed. : null; // The situation has changed. } // 计算等待时间 long waitNanos = node.remainingNanos(System.nanoTime()); // The head of the queue hasn't timed out yet. Await that. if (waitNanos > 0) { // Waiting is made complicated by the fact that we work in nanoseconds, // but the API wants (millis, nanos) in two arguments. long waitMillis = waitNanos / 1000000L; waitNanos -= (waitMillis * 1000000L); // 调用 wait AsyncTimeout.class.wait(waitMillis, (int) waitNanos); return null; } // 第一个节点超时,移除并返回这个节点 head.next = node.next; node.next = null; return node; }
与 enter
相反,exit
则是视状况抛出异常而且移除链表中的节点,这里就不放具体代码了。
Okio 经过 Timeout
以及 AsyncTimeout
分别提供了同步超时和异步超时功能,同步超时是在每次读取数据前判断是否超时,异步超时则是将 AsyncTimeout
组成有序链表,而且开启一个线程来监控,到达超时则触发相关操做。
若是个人文章对您有帮助,不妨点个赞支持一下(^_^)