From 90047b0b5f2df9cdd61a6460afd1aa119d3c8911 Mon Sep 17 00:00:00 2001 From: Norman Maurer Date: Mon, 10 Mar 2014 19:53:16 +0100 Subject: [PATCH] Use bitwise operations to choose next EventExecutor if number of EventExecutors is power of two --- .../MultithreadEventExecutorGroup.java | 31 ++++++++++++++++++- 1 file changed, 30 insertions(+), 1 deletion(-) diff --git a/common/src/main/java/io/netty/util/concurrent/MultithreadEventExecutorGroup.java b/common/src/main/java/io/netty/util/concurrent/MultithreadEventExecutorGroup.java index 9c30d3acbb..9ad7805207 100644 --- a/common/src/main/java/io/netty/util/concurrent/MultithreadEventExecutorGroup.java +++ b/common/src/main/java/io/netty/util/concurrent/MultithreadEventExecutorGroup.java @@ -34,6 +34,7 @@ public abstract class MultithreadEventExecutorGroup extends AbstractEventExecuto private final AtomicInteger childIndex = new AtomicInteger(); private final AtomicInteger terminatedChildren = new AtomicInteger(); private final Promise terminationFuture = new DefaultPromise(GlobalEventExecutor.INSTANCE); + private final EventExecutorChooser chooser; /** * Create a new instance. @@ -63,6 +64,12 @@ public abstract class MultithreadEventExecutorGroup extends AbstractEventExecuto } children = new EventExecutor[nThreads]; + if (isPowerOfTwo(children.length)) { + chooser = new PowerOfTwoEventExecutorChooser(); + } else { + chooser = new GenericEventExecutorChooser(); + } + for (int i = 0; i < nThreads; i ++) { boolean success = false; try { @@ -116,7 +123,7 @@ public abstract class MultithreadEventExecutorGroup extends AbstractEventExecuto @Override public EventExecutor next() { - return children[Math.abs(childIndex.getAndIncrement() % children.length)]; + return chooser.next(); } /** @@ -208,4 +215,26 @@ public abstract class MultithreadEventExecutorGroup extends AbstractEventExecuto } return isTerminated(); } + + private static boolean isPowerOfTwo(int val) { + return (val & -val) == val; + } + + private interface EventExecutorChooser { + EventExecutor next(); + } + + private final class PowerOfTwoEventExecutorChooser implements EventExecutorChooser { + @Override + public EventExecutor next() { + return children[childIndex.getAndIncrement() & children.length - 1]; + } + } + + private final class GenericEventExecutorChooser implements EventExecutorChooser { + @Override + public EventExecutor next() { + return children[Math.abs(childIndex.getAndIncrement() % children.length)]; + } + } }