如何理解Vertx中的Handler为异步执行

刚接触Vertx时,对于函数、响应式编程很是头疼。由其对其中的Handler为异步调用更是不解,翻看Handler源码,其实就是一个接口,方便用于lambda表达式。Handler源码如下:

@FunctionalInterface
public interface Handler {

  /**
   * Something has happened, so handle it.
   *
   * @param event  the event to handle
   */
  void handle(E event);
}

实际异步调用是在使用Vertx方法时给包装成了异步,然后handler的方法在异步线程中被通知执行。我们看下vertx中setTime方法源码。

  public long setTimer(long delay, Handler handler) {
    return scheduleTimeout(getOrCreateContext(), handler, delay, false);
  }
  private long scheduleTimeout(ContextImpl context, Handler handler, long delay, boolean periodic) {
    if (delay < 1) {
      throw new IllegalArgumentException("Cannot schedule a timer with delay < 1 ms");
    }
    long timerId = timeoutCounter.getAndIncrement();
    // 创建定时任务
    InternalTimerHandler task = new InternalTimerHandler(timerId, handler, periodic, delay, context);
    timeouts.put(timerId, task);
    context.addCloseHook(task);
    return timerId;
  }
    InternalTimerHandler(long timerID, Handler runnable, boolean periodic, long delay, ContextImpl context) {
      this.context = context;
      this.timerID = timerID;
      this.handler = runnable;
      this.periodic = periodic;
      this.cancelled = new AtomicBoolean();
      EventLoop el = context.nettyEventLoop();
      // 此处将handler跟随整个this对象一起赋值到运行环境
      Runnable toRun = () -> context.runOnContext(this);
      // 调用netty框架的定时任务,实际执行线程池为vert.x-eventloop-thread
      if (periodic) {
        future = el.scheduleAtFixedRate(toRun, delay, delay, TimeUnit.MILLISECONDS);
      } else {
        future = el.schedule(toRun, delay, TimeUnit.MILLISECONDS);
      }
      if (metrics != null) {
        metrics.timerCreated(timerID);
      }
    }

你可能感兴趣的:(JAVA,Vertx)