一个无状态Select
@NotThreadSafe
public class StatelessFactoreizer implements Servlet {
private Long count = 0L;
public Long getCount() {
return count;
}
@Override
public void service(ServletRequest servletRequest, ServletResponse servletResponse) throws ServletException, IOException {
++count;
}
}
延迟初始化中的竞态条件(不要这么操作)
@NotThreadSafe
public class LazyInitRace {
private ExportException exception = null;
public ExportException getException() {
if (exception == null)
exception = new ExportException("test");
return exception;
}
}
使用AtomicLong类型的变量来统计已处理请求信息
@ThreadSafe
public class CountingFactorizer implements Servlet {
private final AtomicLong count = new AtomicLong();
@Override
public void service(ServletRequest servletRequest, ServletResponse servletResponse) throws ServletException, IOException {
count.incrementAndGet();
}
}
如果内置锁不是可重入的,那么这块代码将发生死锁
public class Widget {
public synchronized void doSemet(){
}
}
public class LoggingWidget extends Widget {
public synchronized void doSemet(){
System.out.printf(toString()+":doSemet");
super.doSemet();
}
}