EJB 3.1容器管理并发与同步 [英] EJB 3.1 container managed concurrency vs. synchronized

查看:141
本文介绍了EJB 3.1容器管理并发与同步的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经开始阅读单例会话bean和用于使用容器管理并发的注释。我没有看到这个结果相比,简单地使用'synchronized'关键字,所以我怀疑有一些重要的我缺少。考虑这个例子,来自Rubinger& Sons的 Enterprise JavaBeans 3.1 Burke,O'Reilly:

I've started reading about the singleton session bean and the annotations used to employ container managed concurrency. I don't see the benfit of this compared to simply using the 'synchronized' keyword, so I suspect there is something important I am missing. Consider this example from the book "Enterprise JavaBeans 3.1" by Rubinger & Burke, O'Reilly:

@javax.ejb.Lock(javax.ejb.LockType.READ)
public String concurrentReadOnlyMethod(){...}

@javax.ejb.Lock(javax.ejb.LockType.WRITE)
public void allowOnlyOneWriteAtATimeMethod(String stringToSet){...}

这比在读取的情况下省略注释以及使用 synchronized 关键字,如下:

How is this better than omitting the annotation all toghether in the read-case and using the synchronized keyword in the write-case, like this:

public String concurrentReadOnlyMethod(){...}

public synchronized void allowOnlyOneWriteAtATimeMethod(String stringToSet){...}


推荐答案

简单。

concurrentReadOnlyMethod完全不同步,因此不会获得其他副作用同步(例如对存储器模型内的变量的影响)。此外,READ锁将阻塞WRITE锁,所以只要同步,你可以有两个线程同时运行这两种方法,而使用READ / WRITE锁,你不会。

The "concurrentReadOnlyMethod" is not synchronized at all, so it doesn't gain other side effect of synchronization (such as effects on variables within the memory model). Also, the READ lock will block the WRITE lock, so with just synchronized, you can have two threads running both methods simultaneously, whereas with the READ/WRITE lock you won't.

显然,当有多个READ锁和几个WRITE锁时,有更多的价值,因为所有的READ锁可以共享并同时运行,而WRITE锁更像是一个正常的同步。

Obviously there's more value when you have several READ locks and few WRITE locks, as all of the READ locks can be shared and run simultaneously, while the WRITE locks act more like a normal synchronized.

这篇关于EJB 3.1容器管理并发与同步的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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