1. 对象逸出(Escape)
构造函数中,当前对象还没初始化完成就暴露this给外部
package com.chstudy.unsafe;
import java.util.ArrayList;
import java.util.List;
public class EventEscape {
private final List<Event> listOfEvents;
public EventEscape(EventSource source) {
source.registerListener(new EventListener() {
@Override
public void onEvent(Event e) {
doSomething(e);
}
});
listOfEvents = new ArrayList<>();
}
void doSomething(Event e) {
listOfEvents.add(e);
}
interface Event {
}
interface EventSource {
void registerListener(EventListener listener);
}
interface EventListener {
void onEvent(Event event);
}
}
二、并发使用的类,对成员变量的访问需要同步
package com.chstudy.unsafe;
import javax.servlet.*;
import javax.servlet.annotation.WebServlet;
import java.io.IOException;
@WebServlet(urlPatterns = "/count.do")
public class UnsafeCountServlet extends GenericServlet implements Servlet {
private Long count = 0L;
public Long getCount() {
return count;
}
@Override
public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException {
try {
Thread.sleep(50);
} catch (InterruptedException e) {
e.printStackTrace();
}
count++;
res.getWriter().write(count+"");
res.flushBuffer();
}
}
三、JVM 参数,打印指定方法的汇编指令
-XX:+UnlockDiagnosticVMOptions -Xcomp -XX:+PrintAssembly -XX:CompileCommand=compileonly,*GoalNotifier.setGoal
-XX:+UnlockDiagnosticVMOptions -XX:+PrintAssembly:开启JIT反汇编
-Xcomp:让虚拟机以编译模式执行代码,使得JIT编译可以立即触发 -XX:CompileCommand=compileonly,*GoalNotifier.setGoal:只反汇编GoalNotifier的setGoal方法
四、