1.方法内连
public interface Animal {
void eat();
}
public class Cat implements Animal {
@Override
public void eat() {
System.out.println("Cat eat !");
}
}
public class Demo {
public void execute(Animal animal){
animal.eat();
}
}
public void execute() {
System.out.println("Cat eat !");
}
2.逃逸分析
逃逸分析指的是根据运行状况来判断方法中变量是否会被方法外部读取,如果被外部读取,则认为是逃逸的。
2.1 栈上分配
Point point = new Point(1, 2);
System.out.println("point.x = " + point.x + "; point.y" + point.y);
如果point
没有逃逸,那么C2会选择在栈上直接创建point
对象,而非堆上。
2.2 锁消除
Point point = new Point(1, 2);
synchronized(point) {
System.out.println("point.x = " + point.x);
}
经过分析如果发现point
未逃逸,则代码会在编译后变成如下结构
Point point = new Point(1, 2);
System.out.println("point.x = " + point.x);