gpt4 book ai didi

java - Servlet 工具箱共享方法的线程安全

转载 作者:行者123 更新时间:2023-11-30 11:23:54 25 4
gpt4 key购买 nike

我对线程相当陌生,我已经阅读了大量关于堆栈溢出的 Q/A 大约一周了。我有一个问题,我找不到明确的答案。我希望你可以帮助我。这是一个示例代码:

public class servlet1 extends HttpServlet {
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
HashMap<String,String> map = null;
... // add some entries to the hash map
ArrayList<String> info = Toolbox.extractInformation(map);
// 1. use the info to generate the response to the client
// 2. Send response to the client
// <End>
}
}

public class servlet2 extends HttpServlet {
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
HashMap<String,String> map = null;
... // add some entries to the hash map
ArrayList<String> info = Toolbox.extractInformation(map);
// 1. use the info to generate the response to the client
// 2. Send response to the client
// <End>
}
}

public class Toolbox {
public static ArrayList<String> extractInformation(HashMap<String,String> map) {
...
}
}

在当前情况下,我有 2 个(或更多)Servlet,它们都使用没有任何同步的公共(public)工具箱方法。据我所知,这应该是线程安全的,因为每个线程都会在它自己的堆栈中创建方法和方法参数的副本并独立执行。工具箱方法不使用实例变量,仅使用传递的参数。它操作参数并返回另一个对象,在本例中为 ArrayList知道容器可能在同一个 servlet 实例上执行多个线程
我的问题是:

  • Toolbox.extractInformation(...) 是否被认为是线程安全的?

感谢您的帮助

谢谢

最佳答案

您的直觉是正确的 - 这里确实存在基于线程的问题的机会:

    HashMap<String,String> map = null;
... // add some entries to the hash map
ArrayList<String> info = Toolbox.extractInformation(map);

如果你的意思是:

    HashMap<String,Object> map = new HashMap<String,Object>();
... // add some entries to the hash map
ArrayList<String> info = Toolbox.extractInformation(map);

在这种情况下,只要您不将相同的对象添加到两个中的映射...//将一些条目添加到散列映射部分在两个线程中,那么你很好。

    static final Object anObject = new Object();
...

HashMap<String,Object> map = new HashMap<String,Object>();
// Share anObject in many threads.
map.put(anObject);
... // add some entries to the hash map
ArrayList<String> info = Toolbox.extractInformation(map);

但是 - 因为您使用的是 String:

    HashMap<String,String> map = new HashMap<String,String>();
... // add some entries to the hash map
ArrayList<String> info = Toolbox.extractInformation(map);

您应该避免线程问题 - 除非在极少数情况下。

关于java - Servlet 工具箱共享方法的线程安全,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20914415/

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