spring如何设置线程安全的全局变量

  @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
            throws Exception {
        Log.info("完成", App.sqlCount.get());
        Log.info(String.format("finish request... || sql执行次数:%s sql总耗时:%s ms", reqExtProperty.sqlCount.get(), App.sqlDuration.get()));
        App.sqlCount.remove();
        App.sqlDuration.remove();
        App._uniq_req_no.remove();
    }
public class App {

    public static final String SESSION_USER = "user"; // 用户对象
    public static ThreadLocal<String> _uniq_req_no = new ThreadLocal<String>();
    public static ThreadLocal<Integer> sqlCount = ThreadLocal.withInitial(() -> 0);
    public static ThreadLocal<Long> sqlDuration = ThreadLocal.withInitial(() -> 0L);
}

发现我这样竟然是线程不安全的。

阅读 3.5k
1 个回答

已经是ThreadLocal了,按说不会有线程不安全的情况,所以题主遇到了什么样的线程不安全呢?

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题