okhttp3源码分析之AsyncTimeout

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/yangshuaionline/article/details/89091724

继承自Timeout,
使后台线程在发生超时时准确执行操作。用来实现本机不支持的超时。

公开方法:

  1. final void enter()

调用了private static synchronized void scheduleTimeout,确定链表关系(当前node上个的next和this的header前后关系)。

private static synchronized void scheduleTimeout(
      AsyncTimeout node, long timeoutNanos, boolean hasDeadline) {
    // Start the watchdog thread and create the head node when the first timeout is scheduled.
    if (head == null) {
      head = new AsyncTimeout();
      new Watchdog().start();
    }

   	...

    // Insert the node in sorted order.
    long remainingNanos = node.remainingNanos(now);
    for (AsyncTimeout prev = head; true; prev = prev.next) {
      //next为空或者截止时间未到
      if (prev.next == null || remainingNanos < prev.next.remainingNanos(now)) {
        node.next = prev.next;
        prev.next = node;
        ...
        break;
      }
    }
  }
  1. public final boolean exit()

调用 cancelScheduledTimeout(AsyncTimeout node)取消预定,如果发生超时(当前链表中没有this)返回true。

private static synchronized boolean cancelScheduledTimeout(AsyncTimeout node) {
    // Remove the node from the linked list.
    for (AsyncTimeout prev = head; prev != null; prev = prev.next) {
      if (prev.next == node) {
        prev.next = node.next;
        node.next = null;
        return false;
      }
    }
    // The node wasn't found in the linked list: it must have timed out!
    return true;
  }
  1. public final Sink sink(final Sink sink)

返回一个接收字节流。使用此接口可在任何需要的地方写入数据:网络,存储或内存中的缓冲区,可以对接收器进行分层以转换所接收的数据,例如压缩,加密,限制或添加协议帧。

  1. public final Source source(final Source source)

返回一个提供字节流,使用此接口可以从任何位置读取数据:来自网络,存储或内存中的缓冲区。 源可以分层以转换所提供的数据,例如解压缩,解密或移除协议成帧。

另外引入一个watchdog:

 private static final class Watchdog extends Thread {
    ...
    public void run() {
      while (true) {
        try {
          AsyncTimeout timedOut;
          synchronized (AsyncTimeout.class) {
          	//获取当前node
            timedOut = awaitTimeout();
			...
            // 队列为空(所有都删除了只剩下new的一个header)
            if (timedOut == head) {
              head = null;
              return;
            }
          }
          // Close the timed out node.
          timedOut.timedOut();
        } catch (InterruptedException ignored) {
        }
      }
    }
  }

猜你喜欢

转载自blog.csdn.net/yangshuaionline/article/details/89091724