ServletContext对象的线程安全性 [英] Thread Safety of ServletContext objects

查看:865
本文介绍了ServletContext对象的线程安全性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在我的ServletContext中存储了一个HashMap对象。
但是多个请求线程正在读取并修改此HashMap。

I am storing a HashMap object in my ServletContext. But Multiple Request thread are reading and Modifying this HashMap.

因为我相信ServletContext对象在请求线程之间共享我是否需要同步对此的访问权限哈希地图?或者还有其他更好的方法来实现相同的目标吗?

As i belive the ServletContext objects are shared between request threads do i need to Synchronize the access to this HashMap ? Or is there any other better ways to achive the same ?

推荐答案

通过 ServletContext#setAttribute <发布属性/ code>是线程安全的!这可以从Java Servlet规范第4.5章中得出:(...)将
绑定到上下文中的任何属性都可用于属于同一Web
应用程序的任何其他servlet。 (...)

(原因:使对象可用于其他servlet也意味着它们可供其他线程使用。这是唯一可行的,如果使用正确的同步,因此 ServletContext #setAttribute )必须同步。

(Reason: Making objects available to other servlets means also to make them available to other threads. This is only possible, if proper synchronization is used, so synchronization is mandatory for ServletContext#setAttribute).

所以同样的情况也是如此通过 ServletContext#getAttribute 读取已发布的属性。

So the same is also true for reading published attributes via ServletContext#getAttribute.

当然,如果像这样的对象HashMap 在不同的线程之间共享,开发人员必须确保以适当的线程安全方式访问此共享对象本身!如问题的其他答案中所述,使用 ConcurrentHashMap 是一种可能的解决方案,但在初始化属性时无法解决竞争条件,如 null check不是原子的:

But of course if an object like a HashMap is shared between different threads, the developer must ensure that this shared object itself is accessed in a proper, thread-safe way! Using a ConcurrentHashMap as already stated in other answers of your question, is a possible solution, but does not solve the race condition when the attribute is initialized, as the null check will not be atomic:

ConcurrentMap<String, Object> shared = (...)servletContext.getAttribute("sharedData");
if (shared == null) {
    shared = new ConcurrentHashMap<>();
    servletContext.setAttribute("sharedData", shared);
}

因此, ServletContextListener 可用于在Web应用程序启动时初始化上下文!

Therefore, a ServletContextListener can be used to initialize the context when the web application starts!

这篇关于ServletContext对象的线程安全性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆