如何从Web服务访问共享资源?

编程入门 行业动态 更新时间:2024-10-24 18:22:46
本文介绍了如何从Web服务访问共享资源?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我读到在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 相同的方法,以及 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 puts, 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服务访问共享资源?

本文发布于:2023-11-08 14:15:34,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1569604.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:共享资源   Web

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!