Javaバイアスロック
import java.util.Random;
import java.util.concurrent.*;
/**
* Created by Administrator on 2016/1/27.
* JDK 1.8.0_65
*/
public class Test5 {
private static final int NTHREAD = 4;
private static final int COUNTER = 10000000;
private static Random random = new Random(123);
private static ExecutorService es1 = Executors.newSingleThreadExecutor();
private static ExecutorService es2 = Executors.newFixedThreadPool(NTHREAD);
private static ThreadLocal<Random> tl = new ThreadLocal<Random>() {
@Override
protected Random initialValue() {
return new Random(123);
}
};
private static class Task implements Callable<Long> {
private int mode = 0;
public Task(int mode) {
this.mode = mode;
}
public Random getRandom() {
if (mode == 0) {
return random;
} else if (mode == 1) {
return tl.get();
}else
return null;
}
@Override
public Long call() throws Exception {
long start = System.currentTimeMillis();
for(long i = 0; i < COUNTER; i++) {
getRandom().nextInt();
}
long end = System.currentTimeMillis();
System.out.println(Thread.currentThread().getName() + "spend " + (end - start) + " ms");
return (end - start);
}
}
public static void main(String... args) throws ExecutionException, InterruptedException {
Future<Long> futs1 = es1.submit(new Task(0));
long time1 = 0;
time1 += futs1.get();
System.out.println("+UseBiasedLocking : " + time1 + " ms");
//System.out.println("-UseBiasedLocking : " + time1 + " ms");
es1.shutdown();
Future<Long>[] futs2 = new Future[NTHREAD];
for(int i = 0; i < NTHREAD ; i++) {
futs2[i] = es2.submit(new Task(0));
}
long time2 = 0;
for(int i = 0; i < NTHREAD ; i++) {
time2 += futs2[i].get();
}
System.out.println("N Thread access one Random instance : " + time2 + " ms");
for(int i = 0; i < NTHREAD ; i++) {
futs2[i] = es2.submit(new Task(1));
}
long time3 = 0;
for(int i = 0; i < NTHREAD ; i++) {
time3 += futs2[i].get();
}
System.out.println("ThreadLocal access one Random instance : " + time3 + " ms");
es2.shutdown();
}
}
//バイアスロックを使用すると、単一スレッド時間は減少することが明らかになりますが、マルチスレッド時間はpool-1-thread-1 spend 563 ms+UseBiasedLocking:563 msを延長します.
pool-2-thread-4spend 2121 mspool-2-thread-2spend 2130 mspool-2-thread-3spend 2309 mspool-2-thread-1spend 2310 msN Thread access one Random instance : 8870 mspool-2-thread-2spend 1563 mspool-2-thread-4spend 1714 mspool-2-thread-1spend 1603 mspool-2-thread-3spend 1784 msThreadLocal access one Random instance : 6664 ms
//明らかに偏向ロックを無効にし、単一スレッド時間は延長するが、マルチスレッド時間は減少する-UseBiasedLockingpool-1-thread-1 spend 760 ms-UseBiasedLocking:760 ms
pool-2-thread-1spend 1153 mspool-2-thread-3spend 1141 mspool-2-thread-4spend 1713 mspool-2-thread-2spend 2081 msN Thread access one Random instance : 6088 mspool-2-thread-1spend 1131 mspool-2-thread-3spend 1027 mspool-2-thread-4spend 1463 mspool-2-thread-2spend 1648 msThreadLocal access one Random instance : 5269 ms