JDK1.6提出了锁的一些优化,有些小伙伴(有些小伙伴系列)可能只知道synchronized锁升级的过程是在1.6提出的,其实还有好些优化的概念都被提出来了,下面详细介绍一下其中的两种优化技术。
-
锁粗化
避免频繁的加锁释放锁,引起线程的内核态和用户态切换
public class TestLockSize {
public void main(String[] args) {
for (int i = 0; i < 10; i++) {
synchronized (this){
System.out.println(Thread.currentThread().getName() + "execute" + i);
}
}
}
/*优化以后的代码*/
public void main1(String[] args) {
synchronized (this){
for (int i = 0; i < 10; i++) {
System.out.println(Thread.currentThread().getName() + "execute" + i);
}
}
}
}
-
锁消除
/**
* @description: 演示锁消除, 临界资源没有逃逸出方法,属于线程私有
* @author: Ding Yawu
* @create: 2022/3/16 22:14
*/
public class TestMethodEscape {
public static void main(String[] args) {
StringBuffer stringBuffer = new StringBuffer();
for (int i = 0; i < 10; i++) {
stringBuffer.append(i);
}
System.out.println(stringBuffer.toString());
}
}