一、局部变量,不存在线程安全问题,因为每个请求都是一个线程请求,局部变量都在线程内不共享
public int sayHello(int count) {
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
e.printStackTrace();
}
count++;
return count;
}
二、全局变量,存在线程安全问题,全局变量是共享数据
private int count = 0;
public int sayHello() {
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
e.printStackTrace();
}
count++;
return count;
}
三、spring单例模式下,资源是否是线程安全的,跟是不是单例没关系,主要看资源是否存在共享情况,如果存在共享情况,在需要解决线程安全问题,例如 SimpleDateFormat
1、synchronize
2、变成局部变量,每次在方法中new SimpleDateFormat(); (不推荐)
3、ThreadLocal<SimpleDateFormat>
//使用ThreadLocal代替原来的new SimpleDateFormat
private static final ThreadLocal<SimpleDateFormat> dateFormatter = new ThreadLocal<SimpleDateFormat>(){
@Override
protected SimpleDateFormat initialValue() {
return new SimpleDateFormat("yyyy-MM-dd");
}
};
@Override
public String today(String POGroup) {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
return dateFormatter.get().format(new DateTime().withZone(DateTimeZone.forID(this.timeZoneMapping.get(POGroup))).toLocalDateTime().toDate());
}