刚接触Vertx时,对于函数、响应式编程很是头疼。由其对其中的Handler为异步调用更是不解,翻看Handler源码,其实就是一个接口,方便用于lambda表达式。Handler源码如下:
@FunctionalInterface
public interface Handler<E> {
/**
* 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<Long> handler) {
return scheduleTimeout(getOrCreateContext(), handler, delay, false);
}
private long scheduleTimeout(ContextImpl context, Handler<Long> 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(tim