下面列出了怎么用io.netty.channel.SingleThreadEventLoop的API类实例代码及写法,或者点击链接到github查看源代码。
public static Map<String, Object> getPoolInfo(EventLoopGroup executors) {
Map<String, Object> info = new HashMap<>(3);
int poolSize = 0, queueSize = 0, activeCount = 0;
for (EventExecutor e : executors) {
poolSize++;
if (e instanceof SingleThreadEventLoop) {
SingleThreadEventLoop executor = (SingleThreadEventLoop) e;
queueSize += executor.pendingTasks();
ThreadProperties tp = executor.threadProperties();
if (tp.state() == Thread.State.RUNNABLE) {
activeCount++;
}
}
}
info.put("poolSize(workThread)", poolSize);
info.put("activeCount(workingThread)", activeCount);
info.put("queueSize(blockedTask)", queueSize);
return info;
}
/**
* Execute the provided task in the EventLoopGroup only once there
* are no more running/queued tasks (but might be future scheduled tasks).
* The key thing here is that it will continue to wait if new tasks
* are scheduled by the already running/queued ones.
*/
private void executeWhenIdle(Runnable task) {
AtomicInteger remainingTasks = new AtomicInteger(-1);
// Two "cycles" are performed, the first with remainingTasks == -1.
// If remainingTasks > 0 after the second cycle, this method
// is re-called recursively (in an async context)
CyclicBarrier cb = new CyclicBarrier(internalExecutor.executorCount(), () -> {
int rt = remainingTasks.get();
if (rt == -1) {
remainingTasks.incrementAndGet();
} else if (rt > 0) {
executeWhenIdle(task);
} else {
internalExecutor.execute(task);
}
});
internalExecutor.forEach(ex -> ex.execute(new Runnable() {
@Override public void run() {
SingleThreadEventLoop stel = (SingleThreadEventLoop) ex;
try {
if (stel.pendingTasks() > 0) {
ex.execute(this);
} else {
cb.await();
if (stel.pendingTasks() > 0) {
remainingTasks.incrementAndGet();
}
cb.await();
}
} catch (InterruptedException|BrokenBarrierException e) {
Thread.currentThread().interrupt();
}
}
}));
}
@Override
protected boolean isCompatible(EventLoop loop) {
return loop instanceof SingleThreadEventLoop;
}
@Override
protected boolean isCompatible(EventLoop loop) {
return loop instanceof SingleThreadEventLoop;
}
@Override
protected boolean isCompatible(EventLoop loop) {
return loop instanceof SingleThreadEventLoop;
}
@Override
protected boolean isCompatible(EventLoop loop) {
return loop instanceof SingleThreadEventLoop;
}
@Override
protected boolean isCompatible(EventLoop loop) {
return loop instanceof SingleThreadEventLoop;
}
@Override
protected boolean isCompatible(EventLoop loop) {
return loop instanceof SingleThreadEventLoop;
}