EventExecutorChooser体系

392 阅读1分钟

image.png

1 EventExecutorChooser

一个接口,用于选择下一个EventExecutor

2 EventExecutorChooserFactory

一个接口,语义是工厂,一个生产EventExecutorChooser的工厂

3 netty中EventExecutorChooser的默认实现GenericEventExecutorChooser

GenericEventExecutorChooser中存放了一个EventExecutor的数组,你调用next,它会一直做轮询,到尾部元素了,就从头部元素接着在来;

private static final class GenericEventExecutorChooser implements EventExecutorChooser {
    // Use a 'long' counter to avoid non-round-robin behaviour at the 32-bit overflow boundary.
    // The 64-bit long solves this by placing the overflow so far into the future, that no system
    // will encounter this in practice.
    private final AtomicLong idx = new AtomicLong();
    private final EventExecutor[] executors;

    GenericEventExecutorChooser(EventExecutor[] executors) {
        this.executors = executors;
    }

    @Override
    public EventExecutor next() {
        return executors[(int) Math.abs(idx.getAndIncrement() % executors.length)];
    }
}

4 netty中EventExecutorChooser的默认实现PowerOfTwoEventExecutorChooser

PowerOfTwoEventExecutorChooser中存放了一个EventExecutor的数组,如果EventExecutor数组的大小是2的几次幂,你调用next,它会一直做轮询,到尾部元素了,就从头部元素接着在来;

private static final class PowerOfTwoEventExecutorChooser implements EventExecutorChooser {
    private final AtomicInteger idx = new AtomicInteger();
    private final EventExecutor[] executors;

    PowerOfTwoEventExecutorChooser(EventExecutor[] executors) {
        this.executors = executors;
    }

    @Override
    public EventExecutor next() {
        return executors[idx.getAndIncrement() & executors.length - 1];
    }
}

5 EventExecutorChooserFactory的默认实现DefaultEventExecutorChooserFactory

newChooser方法的实现,如果EventExecutor[] executors的大小是2的幂次,则new PowerOfTwoEventExecutorChooser否则new GenericEventExecutorChooser;

@Override
public EventExecutorChooser newChooser(EventExecutor[] executors) {
    if (isPowerOfTwo(executors.length)) {
        return new PowerOfTwoEventExecutorChooser(executors);
    } else {
        return new GenericEventExecutorChooser(executors);
    }
}