gpt4 book ai didi

Java : Using static variable to store Application Specifc Data inside a web based Application

转载 作者:行者123 更新时间:2023-12-02 00:12:11 25 4
gpt4 key购买 nike

我正在开发一个现有的基于 Web 的应用程序,该应用程序使用静态 map 来存储特定于应用程序的数据。

下面是我的代码,它负责将数据存储在 ConcurrentHashMap 中,如下所示。

public class MyClass 

// Class variable
private static Map<String, UserThread> usermap = new ConcurrentHashMap<String, UserThread>();

// Inside a Method
public void userData()
{
UserThread userThread= usermap.get(getLoginId());
if (userThread == null) {
userThread = new UserThread();
userThread.start();
usermap.put(getLoginId(), userThread);
}
}

应用程序工作正常,我的问题是,这是一个有效的代码,因为我们可以将数据存储在静态变量中吗? (这里静态ConcurrentHashMap包含特定于应用程序的数据)

最佳答案

应避免使用任何类型的静态变量和缓存,尤其是在 Web 应用程序等多线程环境中。您的代码存在几个问题:

  1. 您是否从 map 中删除 UserThreads?你怎么知道什么时候应该删除它们?如果客户端的浏览器崩溃怎么办?如果您不删除它们,则会在应用程序运行一段时间后出现内存不足错误。
  2. 以您使用的方式使用 ConcurrentHashMap 不是线程安全的,因为另一个线程可能会在 if (userThread == null)usermap.put(getLoginId) 之间添加 UserThread (), userThread); . HashMap 的并发版本并没有像看起来那样神奇地解决所有线程安全问题。
  3. 在 servlet 容器中生成您自己的线程并不是一个好主意。有更好的方法来执行后台任务,但首先您需要说明线程正在尝试执行的操作。

通常,在任何类型的应用程序中使用任何类型的此类静态缓存都是坏主意。在您的情况下,最好将应用程序特定的数据保留在用户 session 中。

关于Java : Using static variable to store Application Specifc Data inside a web based Application ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12562984/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com