ThreadLocalRandom研究

ThreadLocalRandom研究

经过调试,发现JDK1.8中使用ThreadLocalRandom生成随机数只与下边这个初始化种子的函数initialSeed有关系,默认情况下使用System.currentTimeMillis()System.nanoTime()运算后作为种子。

image-20210806092248585

使用Java Bytecode Editor修改ThreadLocalRandom的class文件,使initialSeed返回固定的值。

image-20210806093019908

再利用javassist在类加载时替换class文件。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
public class FirstAgent implements ClassFileTransformer {
public final String injectedClassName = "java.util.concurrent.ThreadLocalRandom";
@Override
public byte[] transform(ClassLoader loader, String className, Class<?> classBeingRedefined, ProtectionDomain protectionDomain, byte[] classfileBuffer) throws IllegalClassFormatException {
className = className.replace("/", ".");
if (className.equals(injectedClassName)) {
System.out.println(className);
CtClass ctclass = null;
try {
ctclass = ClassPool.getDefault().makeClass(new FileInputStream("ThreadLocalRandom.class"));
return ctclass.toBytecode();
} catch (Exception e) {
System.out.println(e.getMessage());
e.printStackTrace();
}
}
return null;
}
}

最终可以看到生成的随机数序列固定。

image-20210806092127939

image-20210806092032188