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#
| Modifier and Type | Field and Description |
|---|---|
| private static final int | BIT_INDEX_MASK
Mask to extract the bit offset within a byte (0-7) |
| private int | bitIndex
Index of the next bit in the cache to be used. |
| private static final int | BITS_PER_BYTE
Number of bits in a byte |
| private final byte[] | |
| private static final int | MAX_BITS
Maximum number of bits that can be generated (size of an int) |
| private static final int | MAX_CACHE_SIZE
The maximum size of the cache. |
| private final Random |
| Access | Constructor and Description |
|---|---|
| pack-priv | CachedRandomBits(final int
number of bytes cached (only affects performance) cacheSize, final Random random source random)Creates a new instance. |
| Modifier and Type | Method and Description |
|---|---|
| public int | Returns: random integer containing exactly the requested number of random bitsnumber of bits to generate, MUST be between 1 and 32 (inclusive) bits)Generates a random integer with the specified number of bits. |
| BIT_INDEX_MASK | back to summary |
|---|---|
| private static final int BIT_INDEX_MASK Mask to extract the bit offset within a byte (0-7) | |
| bitIndex | back to summary |
|---|---|
| private int bitIndex Index of the next bit in the cache to be used.
| |
| BITS_PER_BYTE | back to summary |
|---|---|
| private static final int BITS_PER_BYTE Number of bits in a byte | |
| cache | back to summary |
|---|---|
| private final byte[] cache | |
| MAX_BITS | back to summary |
|---|---|
| private static final int MAX_BITS Maximum number of bits that can be generated (size of an int) | |
| MAX_CACHE_SIZE | back to summary |
|---|---|
| private static final int MAX_CACHE_SIZE The maximum size of the cache.
This is to prevent the possibility of overflow in the | |
| random | back to summary |
|---|---|
| private final Random random | |
| CachedRandomBits | back to summary |
|---|---|
| pack-priv CachedRandomBits(final int cacheSize, final Random random) Creates a new instance.
| |
| nextBits | back to summary |
|---|---|
| public int nextBits(final int bits) Generates a random integer with the specified number of bits. This method efficiently generates random bits by using a byte cache and bit manipulation:
| |