风一更--软件开发--Java web 并发性安全

目的:准确高效的 Java web 技能


1. Spring Bean 的安全性要由开发者来保证.

最好无状态,

有状态则用 ThreadLocal 来用空间换安全.

参考:

1.https://www.cnblogs.com/myhomepages/p/16510531.html

2.https://dzone.com//articles/painless-introduction-javas-threadlocal-storage

public class ConnectionWrapper {

  public static String DB_URL = "mock database url";
  private static ThreadLocal<Connection> connectionHolder =
      new ThreadLocal<>() {
        public Connection initialValue() {
          try {
            return DriverManager.getConnection(DB_URL);
          } catch (SQLException e) {
            throw new RuntimeException(e);
          }
        }
      };

  public static Connection getConnection() {
    return connectionHolder.get();
  }
  
  // 使用完使用 ThreadLocal remove(entry) 防止泄露
}

3. spring controller, 安全性

https://www.bbsmax.com/A/RnJW6Kxozq/

threadLocal :

https://www.cnblogs.com/myhomepages/p/16510531.html

4. ThreadLocal 要在最初就初始化,不要采用以下方式:

问题在于第二个线程来取值时,会得到 null

public class NotSafeCounter {
  private static ThreadLocal<Integer> counter = new ThreadLocal<>();
  static{
      counter.set(0);
  }
  public int getCountInThread(){
      return counter.get();
  }
}
posted @ 2023-02-18 15:02  君子之行  阅读(11)  评论(0)    收藏  举报