Java需要掌握的底层知识_Java程序员应该掌握的底层知识
緩存
緩存行:
緩存行越大,局部性空間效率越高,但讀取時間慢
緩存行越小,局部性空間效率越低,但讀取時間快
取一個折中值,目前多用:
64字節
public class CacheLinePadding { //執行時間在4s左右
public volatile static long[] arr=new long[2];
public static void main(String[] args) throws Exception{
Thread t1=new Thread(()->{
for (long i=0;i< 10_0000_0000L;i++){
arr[0]=i;
}
});
Thread t2=new Thread(()->{
for (long i=0;i< 10_0000_0000L;i++){
arr[1]=i;
}
});
t1.start();
t2.start();
final long start = System.nanoTime();
t1.join();
t2.join();
final long end = System.nanoTime();
System.out.println((end-start)/1000000);
}
}
public class T02_CacheLinePadding { //執行在2s左右
public volatile static long[] arr=new long[16];
public static void main(String[] args) throws Exception{
Thread t1=new Thread(()->{
for (long i=0;i< 10_0000_0000L;i++){
arr[0]=i;
}
});
Thread t2=new Thread(()->{
for (long i=0;i< 10_0000_0000L;i++){
arr[8]=i;
}
});
t1.start();
t2.start();
final long start = System.nanoTime();
t1.join();
t2.join();
final long end = System.nanoTime();
System.out.println((end-start)/1000000);
}
}
緩存行對齊:對于有些特別敏感的數字,會存在線程高競爭的訪問,為了保證不發生偽共享,可以使用緩存航對齊的編程方式
JDK7中,很多采用long padding提高效率
eg:
JDK8,加入了@Contended注解(實驗)需要加上:JVM -XX:-RestrictContended
public class T03_CacheLinePading {
@Contended
volatile long x;
@Contended
volatile long y;
public static void main(String[] args) throws Exception{ //0.6s
T03_CacheLinePading t3=new T03_CacheLinePading();
Thread t1=new Thread(()->{
for (long i=0;i< 1_0000_0000L;i++){
t3.x=i;
}
});
Thread t2=new Thread(()->{
for (long i=0;i< 1_0000_0000L;i++){
t3.y=i;
}
});
t1.start();
t2.start();
final long start = System.nanoTime();
t1.join();
t2.join();
final long end = System.nanoTime();
System.out.println((end-start)/1000000);
}
}
亂序執行
/**
* CPU的亂序執行
*/
public class DisorderTest {
private static int x=0,y=0;
private static int a=0,b=0;
//第44448次 (0,0)
public static void main(String[] args) throws InterruptedException {
int i = 0;
for (; ; ) {
i++;
x = 0;
y = 0;
a = 0;
b = 0;
Thread one = new Thread(new Runnable() {
public void run() {
//由于線程one先啟動,下面這句話讓它等一等線程two. 讀著可根據自己電腦的實際性能適當調整等待時間.
shortWait(100000);
a = 1;
x = b;
}
});
Thread other = new Thread(new Runnable() {
public void run() {
b = 1;
y = a;
}
});
one.start();
other.start();
one.join();
other.join();
String result = "第" + i + "次(" + x + "," + y + ")";
if (x == 0 && y == 0) {
System.err.println(result);
break;
} else {
//System.out.println(result);
}
}
}
public static void shortWait(long interval){
long start = System.nanoTime();
long end;
do{
end = System.nanoTime();
}while(start + interval >= end);
}
}
禁止亂序
CPU層面:Intel -> 原語(mfence lfence sfence) 或者鎖總線
JVM層級:8個hanppens-before原則 4個內存屏障 (LL LS SL SS)
as-if-serial : 不管硬件什么順序,單線程執行的結果不變,看上去像是serial
合并寫
Write Combining Buffer
一般是4個字節
由于ALU速度太快,所以在寫入L1的同時,寫入一個WC Buffer,滿了之后,再直接更新到L2
總結
以上是生活随笔為你收集整理的Java需要掌握的底层知识_Java程序员应该掌握的底层知识的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: android数字滚动动画,Androi
- 下一篇: python删除excel内容_用pyt