Hengliang
5/7/2014 - 3:12 AM

Java Code Gadget

夹娃小玩意,都是些精彩的,奇特的,实用的小代码。💯

Atomic Operation

// From Netty 3.3.1 Final 
//        \_ org.jboss.netty.channel.AbstractChannel

private static Integer allocateId(Channel channel) {
  Integer id = Integer.valueOf(System.identityHashCode(channel));
  for (;;) {
    // Loop until a unique ID is acquired.
    // It should be found in one loop practically.
    if (allChannels.putIfAbsent(id, channel) == null) {
      // Successfully acquired.
      return id;
    } else {
      // Taken by other channel at almost the same moment.
      id = Integer.valueOf(id.intValue() + 1);
    }
  }
}

What is the default maximum heap size for Sun's JVM from Java SE 6?

# Java 1.6.0_21 or later, or so...

$ java -XX:+PrintFlagsFinal -version 2>&1 | grep MaxHeapSize
uintx MaxHeapSize                         := 12660904960      {product}
# It looks like the min(1G) has been removed.

# Or on Windows using findstr

C:\>java -XX:+PrintFlagsFinal -version 2>&1 | findstr MaxHeapSize

UUID

// The following code section is taken from OpenJDK7 but it is identical also used if OracleJDK6:

public static UUID randomUUID() {
  SecureRandom ng = numberGenerator;
  if (ng == null) {
      numberGenerator = ng = new SecureRandom();
  }

  byte[] randomBytes = new byte[16];
  ng.nextBytes(randomBytes);
  randomBytes[6]  &= 0x0f;  /* clear version        */
  randomBytes[6]  |= 0x40;  /* set to version 4     */
  randomBytes[8]  &= 0x3f;  /* clear variant        */
  randomBytes[8]  |= 0x80;  /* set to IETF variant  */
  return new UUID(randomBytes);
}

Are Java random UUID's predictable?