在实现 EJBHomeFactory 模式时是否需要同步 Map?
当您想要从客户端调用 EJBBean
时,首先需要通过 JNDI 查找获取 EJBHome
对象引用。每次需要使用 EJBBean
时都需要执行此代码,因此变得多余且昂贵。
要解决此问题,您可以缓存 EJBHome
对象引用并从缓存中一次又一次地重用它们,而无需重复 JNDI 查找。
这是 EJBHomeFactory 模式
(或更通用的服务定位器模式)。
我见过的大多数实现都使用同步Map
作为缓存,或Hashtable
。如果在将应用程序部署到服务器上时构建了缓存,并且之后没有对缓存进行任何修改(仅执行 get() 方法),我真的需要一个同步的 Map
或 HashMap
可以吗?
我知道如果至少有一个线程修改了映射,则 HashMap
是不安全的(甚至有一篇关于此的帖子 此处),但在这种情况下,线程仅执行读取。
那么,在 EJBHomeFactory 模式中使用 HashMap 是否安全?
When you want to call an EJBBean
from the client, first you need to get hold of an EJBHome
object reference through JNDI lookup. This code needs to be executed each time you need to work with the EJBBean
so is gets redundant and expensive.
To solve this problem, you can cache the EJBHome
object references and reuse them again and again from the cache without repeating the JNDI lookup.
This is the EJBHomeFactory Pattern
(or a more generic Service Locator Pattern).
The majority of implementations I have seen use a synchronized Map
as the cache, or a Hashtable
. If the cache is constructed when the application is deployed on the server and no modifications are made to the cache afterwards (only get() methods are performed) do I really need a synchronized Map
or a HashMap
will do?
I know HashMap
is not safe if at least one of the threads modifies the map (there is even a SO post on this here) but in this case threads only perform reads.
So, is a HashMap
safe to use in the EJBHomeFactory Pattern
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果您可以保证生命周期如您所描述的那样,那么很明显,不同步的 HashMap 应该没问题。然而,我的直觉是,这建立在对当前部署模式的脆弱依赖之上。
如果您使用同步数据结构,那么您知道它现在和将来都是安全的。除非您有具体证据表明同步确实影响性能,否则我会选择“明显正确”的实现。
顺便说一句,几个领先的应用程序服务器实际上缓存了 JNDI 查找的结果,因此不清楚您使用的模式实际上节省了多少 - 尽管我必须承认我自己确实倾向于使用它。
EJB 引用本身可以重用,因此实际上回家的频率可以保持在相当低的水平。如果极限性能是目标,这可能是进一步探索的途径。
If you can guarantee the life-cycle is as you describe it seems clear that the unsynchronized HashMap should be OK. However, my instinct is that this is building in a brittle dependency on your current deployment pattern.
If you use a synchronized datastructure then you know it's safe now and in the future. Unless you have concrete evidence that the synchronisation is truly impacting performance I would go with the "obviously correct" implementation.
In passing, several leading app servers actually cache the results of JNDI lookups so it's not clear how much saving the pattern your using actually gives - though I must admit I do tend to use it myself.
EJB references themselves can be reused, so in fact the frequency of going to the home can be kept quite low. If extreme performance is the objective this may be a further avenue to explore.