方法generateSecureRandom()
经常被不同的线程调用,我也使用这个 token 来生成数据库ID。
我是否应该将字段 random
和 encoder
放在类级别以使其更高效(线程本地?)?
如果将 random
或 encoder
放在类级别,当一个线程正在使用 SecureRandom
时,其他线程的访问是否会被锁定?我不想创建 SecureRandom 实例池,而是使用线程本地。
public final RandomGenerator{
public static String generateSecureRandom() {
// field will be created on each method call
final SecureRandom random = new SecureRandom();
// field will be created on each method call
final Base64.Encoder encoder = Base64.getUrlEncoder().withoutPadding();
byte[] buffer = new byte[20];
random.nextBytes(buffer);
return encoder.encodeToString(buffer);
}
}
我应该将字段 random
和 encoder
放在方法级别还是类级别?
最佳答案
我认为,使用ThreadLocal
并将random
和encoder
放在类级别比不使用TreadLocal
要好>。
此外,不建议将 random
和 encoder
放在方法级别,因为在每个方法调用上创建 new SecureRandom
的成本非常昂贵。
public final class SecureRandomString {
private SecureRandomString() {
}
// don't use SecureRandom without ThreadLocal,
// because it will block other threads while one thread is using it
// private static final SecureRandom random = new SecureRandom();
// use thread local for high throughput
private static final ThreadLocal<SecureRandom> random = new ThreadLocal<>();
// the encoder does not need a ThreadLocal
// because it is thread safe and no lock is required by accessing it
private static final Base64.Encoder encoder = Base64.getUrlEncoder().withoutPadding();
public static String generate() {
byte[] buffer = new byte[20];
random.get().nextBytes(buffer);
return encoder.encodeToString(buffer);
}
}
关于java - 生成 SecureRandom() 的高性能方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60059184/