Generate channel IDs in a pseudorandom fashion

Requested by @psweeny in #547

Signed-off-by: Cruz Julian Bishop <cruzjbishop@gmail.com>
This commit is contained in:
Cruz Julian Bishop 2012-08-23 09:56:58 +10:00
parent 73720c422d
commit 7e3bfaf24c

View File

@ -24,6 +24,7 @@ import io.netty.util.DefaultAttributeMap;
import java.io.IOException; import java.io.IOException;
import java.net.SocketAddress; import java.net.SocketAddress;
import java.nio.channels.ClosedChannelException; import java.nio.channels.ClosedChannelException;
import java.util.Random;
import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap; import java.util.concurrent.ConcurrentMap;
@ -36,13 +37,19 @@ public abstract class AbstractChannel extends DefaultAttributeMap implements Cha
static final ConcurrentMap<Integer, Channel> allChannels = new ConcurrentHashMap<Integer, Channel>(); static final ConcurrentMap<Integer, Channel> allChannels = new ConcurrentHashMap<Integer, Channel>();
private static final Random random = new Random();
public static Random getRandom() {
return random;
}
/** /**
* Generates a negative unique integer ID. This method generates only * Generates a negative unique integer ID. This method generates only
* negative integers to avoid conflicts with user-specified IDs where only * negative integers to avoid conflicts with user-specified IDs where only
* non-negative integers are allowed. * non-negative integers are allowed.
*/ */
private static Integer allocateId(Channel channel) { private static Integer allocateId(Channel channel) {
int idVal = System.identityHashCode(channel); int idVal = random.nextInt();
if (idVal > 0) { if (idVal > 0) {
idVal = -idVal; idVal = -idVal;
} else if (idVal == 0) { } else if (idVal == 0) {