Class CachedRandomBits


  • final class CachedRandomBits
    extends java.lang.Object
    Generates random integers of specific bit length.

    It is more efficient than calling Random.nextInt(1 << nbBits). It uses a cache of cacheSize random bytes that it replenishes when it gets empty. This is especially beneficial for SecureRandom Drbg implementations, which incur a constant cost at each randomness generation.

    Used internally by RandomStringUtils.

    #NotThreadSafe#

    • Field Summary

      Fields 
      Modifier and Type Field Description
      private int bitIndex
      Index of the next bit in the cache to be used.
      private byte[] cache  
      private java.util.Random random  
    • Constructor Summary

      Constructors 
      Constructor Description
      CachedRandomBits​(int cacheSize, java.util.Random random)
      Creates a new instance.
    • Method Summary

      All Methods Instance Methods Concrete Methods 
      Modifier and Type Method Description
      int nextBits​(int bits)
      Generates a random integer with the specified number of bits.
      • Methods inherited from class java.lang.Object

        clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
    • Field Detail

      • random

        private final java.util.Random random
      • cache

        private final byte[] cache
      • bitIndex

        private int bitIndex
        Index of the next bit in the cache to be used.
        • bitIndex=0 means the cache is fully random and none of the bits have been used yet.
        • bitIndex=1 means that only the LSB of cache[0] has been used and all other bits can be used.
        • bitIndex=8 means that only the 8 bits of cache[0] has been used.
    • Constructor Detail

      • CachedRandomBits

        CachedRandomBits​(int cacheSize,
                         java.util.Random random)
        Creates a new instance.
        Parameters:
        cacheSize - number of bytes cached (only affects performance)
        random - random source
    • Method Detail

      • nextBits

        public int nextBits​(int bits)
        Generates a random integer with the specified number of bits.
        Parameters:
        bits - number of bits to generate, MUST be between 1 and 32
        Returns:
        random integer with bits bits