内存 缓存行 cpu 1级缓存的缓存一致性协议试验方法
package com.dlx.cpu.cache;
public class CacheLinePadding {
public static volatile long[] arr = new long[2];
public static void main(String[] args) throws Exception {
Thread t1 = new Thread(()->{
for (long i = 0; i < 10000_0000L; i++) {
arr[0] = i;
}
});
Thread t2 = new Thread(()->{
for (long i = 0; i < 10000_0000L; i++) {
arr[1] = i;
}
});
final long start = System.nanoTime();
t1.start();
t2.start();
t1.join();
t2.join();
System.out.println((System.nanoTime() - start)/100_0000);
}
}
package com.dlx.cpu.cache;
public class CacheLinePadding {
public static volatile long[] arr = new long[16];
public static void main(String[] args) throws Exception {
Thread t1 = new Thread(()->{
for (long i = 0; i < 10000_0000L; i++) {
arr[0] = i;
}
});
Thread t2 = new Thread(()->{
for (long i = 0; i < 10000_0000L; i++) {
arr[8] = i;
}
});
final long start = System.nanoTime();
t1.start();
t2.start();
t1.join();
t2.join();
System.out.println((System.nanoTime() - start)/100_0000);
}
}
JDK8 支持使用@Contended 来做成员变量在缓存行中唯一变量
本文通过两个Java示例,展示了如何利用缓存行填充技术来优化多线程环境下的内存访问效率,避免伪共享问题。通过对比不同长度数组的线程操作,分析了缓存一致性协议在多核处理器上的作用。
304





