如何从Web服务访问共享资源? [英] How to access shared resource from a Web Service?
问题描述
我读到在Java EE中,Web服务将为每个请求生成一个线程,因此我不必自己进行线程阻塞操作(例如数据库查询)。
I read that in Java EE a Web Service will spawn a thread for every request, so I don't have to thread blocking operations (e.g. database queries) myself.
如何从这种线程调度方法正确访问共享资源?
How would I properly access a shared resource from such thread-dispatched method?
例如。如果我有 SessionManager
,其中包含用户
对象的地图和 loginUser()
允许在JSF上下文之外登录的方法,我如何防止竞争条件?我只是使用互斥锁,还是JavaEE为这个问题提供了解决方案?
e.g. if I have a SessionManager
which contains a map of User
objects and a loginUser()
method to allow logins outside of a JSF context, how would I prevent race conditions? Do I just use mutexes, or does JavaEE provide a solution to this problem?
推荐答案
Java EE不为您提供任何解决方案通过自己的资源进行资源争用的解决方案;但是Java确实如此。
Java EE doesn't provide you with any solution for resource contention over your own resources; but Java does.
对于你的情况,使用 ConcurrentHashMap
可以解决你的大多数问题。 ConcurrentHashMap
将保护您免受两个线程在完全相同的时间内更新 Map
的情况(在 HashMap
,可能会抛出异常)。它为 Map
接口提供了与 HashMap
相同的方法,以及<$ c $中的一些有用方法c> ConcurrentMap 接口(例如替换
和 putIfAbsent
)。对于大多数需求,这个选项就足够了。
For your case, using a ConcurrentHashMap
may solve most of your problems. A ConcurrentHashMap
will protect you against cases in which two threads update the Map
in exactly the same time (which, in a HashMap
, is likely to throw an exception). It offers you the same methods from the Map
interface as HashMap
, plus a few useful methods from the ConcurrentMap
interface (such as replace
and putIfAbsent
). For most needs, this option is sufficient.
尽管如此,有时你可能需要使用 synchronized
关键字,即使您使用的是 ConcurrentHashMap
。例如,考虑一种情况,当你想将两个项目放入 Map
时,但对你来说非常重要的是,当前线程发出两个 put
s,没有其他线程获取
或 put
来自地图。换句话说, ConcurrentHashMap
仅隔离每个调用的访问权限;对于需要隔离以跨越多个呼叫的情况,请使用 synchronized
。
Having said that, sometimes, you might need to use the synchronized
keyword even if you're using a ConcurrentHashMap
. For example, consider a case when you'd like to put two items into the Map
, but it's extremely important to you that, while the current thread is issuing the two put
s, no other thread will get
or put
from the Map. In other words, ConcurrentHashMap
only isolates access for each call individually; for cases when you need the isolation to span multiple calls, use synchronized
.
EDIT 关注@ Arjan的评论:如果你使用的是JavaEE 6.0,你可以将 @Singleton
与组合使用@Lock
达到类似效果。
EDIT following @Arjan's comment: if you're using JavaEE 6.0 onwards, you can use @Singleton
in combination with @Lock
to achieve a similar effect.
这篇关于如何从Web服务访问共享资源?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!