ava EE 7 - Injection into Runnable/Callable object ejb entityManager Concurrency ManagedExecutorService 异步调用如何获取context
或者直接把
MyTask类内嵌如MyBean中,这样可以在myBean中inject 数据库连接,在内嵌类内访问。
java ee 引入了并发执行。因为是在服务器执行并发,所以要用java ee包里面的并发类:javax.enterprise.concurrent.ManagedScheduledExecutorService。并发是异步执行,需要实现run/call函数。由于是异步执行,我们实现类的创建不能用@Inject,因为这样会导致只能创建一个实例。我们也不能用new 创建实例,会导致无法访问容器中的datasource等容器提供的实例。
这种情况下,只能用Instance创建实例。
@Stateless
public class MyBean {
    @Resource
    ManagedExecutorService managedExecutorService;
    @PersistenceContext
    EntityManager entityManager;
    @Inject
    Instance<MyTask> myTaskInstance;
    public void executeAsync() throws ExecutionException, InterruptedException {
    for(int i=0; i<10; i++) {
        MyTask myTask = myTaskInstance.get();
        this.managedExecutorService.submit(myTask);
    }
}
https://martinsdeveloperworld.wordpress.com/2014/02/25/using-java-ees-managedexecutorservice-to-asynchronously-execute-transactions/
https://stackoverflow.com/questions/21078616/java-ee-7-injection-into-runnable-callable-object
Using Java EE’s ManagedExecutorService to asynchronously execute transactions
One year has passed by since the Java EE 7 specification has been published. Now that Wildfly 8 Final has been released, it is time to take a closer look at the new features.
One thing which was missing since the beginning of the Java EE days is the ability to work with fully-fledged Java EE threads. Java EE 6 has already brought us the @Asynchronous annotation with which we could execute single methods in the background, but a real thread pool was still out of reach. But all this is now history since Java EE 7 introduced the ManagedExecutorService:
| 
 1 
2 
 | 
@ResourceManagedExecutorService managedExecutorService; | 
Like the well-known ExecutorService from the Standard Edition, the ManagedExecutorService can be used to submit tasks that are executed within a thread pool. One can choose if the tasks submitted should implement the Runnable or Callable interface.
In contrast to a normal SE ExecutorService instance, the ManagedExecutorService provides threads that can access for example UserTransactions from JNDI in order to execute JPA transactions during their execution. This feature is a huge difference to threads started like in a SE environment.
It is important to know, that the transactions started within the ManagedExecutorService’s thread pool run outside of the scope of the transaction of the thread which submits the tasks. This makes it possible to implement scenarios in which the submitting thread inserts some information about the started tasks into the database while the long-running tasks execute their work within an independent transaction.
Now, after we have learned something about the theory, let’s put our hands on some code. First we write a @Stateless EJB that gets the ManagedExecutorService injected:
| 
 1 
2 
3 
4 
5 
6 
7 
8 
9 
10 
11 
12 
13 
14 
15 
16 
17 
18 
19 
20 
 | 
@Statelesspublic class MyBean {    @Resource    ManagedExecutorService managedExecutorService;    @PersistenceContext    EntityManager entityManager;    @Inject    Instance<MyTask> myTaskInstance;    public void executeAsync() throws ExecutionException, InterruptedException {        for(int i=0; i<10; i++) {            MyTask myTask = myTaskInstance.get();            this.managedExecutorService.submit(myTask);        }    }    public List<MyEntity> list() {        return entityManager.createQuery("select m from MyEntity m", MyEntity.class).getResultList();    }} | 
The tasks that we will submit to the ManagedExecutorService are retrieved from CDI’s Instance mechanism. This lets us use the power of CDI within our MyTask class:
| 
 1 
2 
3 
4 
5 
6 
7 
8 
9 
10 
11 
12 
13 
14 
15 
16 
17 
18 
19 
20 
21 
22 
23 
24 
25 
26 
27 
28 
29 
30 
31 
 | 
public class MyTask implements Runnable {    private static final Logger LOGGER = LoggerFactory.getLogger(MyTask.class);    @PersistenceContext    EntityManager entityManager;    @Override    public void run() {        UserTransaction userTransaction = null;        try {            userTransaction = lookup();            userTransaction.begin();            MyEntity myEntity = new MyEntity();            myEntity.setName("name");            entityManager.persist(myEntity);            userTransaction.commit();        } catch (Exception e) {            try {                if(userTransaction != null) {                    userTransaction.rollback();                }            } catch (SystemException e1) {                LOGGER.error("Failed to rollback transaction: "+e1.getMessage());            }        }    }    private UserTransaction lookup() throws NamingException {        InitialContext ic = new InitialContext();        return (UserTransaction)ic.lookup("java:comp/UserTransaction");    }} | 
Here we can inject the EntityManager to persist some entities into our database. The UserTransaction that we need for the commit has to be retrieved from the JNDI. An injection using the @Resource annotation is not possible within a normal managed bean.
To circumvent the UserTransaction we could of course call the method of another EJB and use the other EJB’s transaction to commit the changes to the database. The following code shows an alternative implementation using the injected EJB to persist the entity:
| 
 1 
2 
3 
4 
5 
6 
7 
8 
9 
10 
11 
12 
13 
 | 
public class MyTask implements Runnable {    private static final Logger LOGGER = LoggerFactory.getLogger(MyTask.class);    @PersistenceContext    EntityManager entityManager;    @Inject    MyBean myBean;    @Override    public void run() {        MyEntity myEntity = new MyEntity();        myBean.persit(myEntity);    }} | 
Now we only need to utilize JAX-RS to call the functionality over a REST interface:
| 
 1 
2 
3 
4 
5 
6 
7 
8 
9 
10 
11 
12 
13 
14 
15 
16 
17 
18 
19 
20 
 | 
@Path("/myResource")public class MyResource {    @Inject    private MyBean myBean;    @Path("list")    @GET    @Produces("text/json")    public List<MyEntity> list() {        return myBean.list();    }    @Path("persist")    @GET    @Produces("text/html")    public String persist() throws ExecutionException, InterruptedException {        myBean.executeAsync();        return "<html><h1>Successful!</h1></html>";    }} | 
That’s it. With these few lines of code we have implemented a fully working Java EE application whose functionality can be called over a REST interface and that executes its core functionality asynchronously within worker threads with their own transactions.
Conclusion: The ManagedExecutorService is a great feature to integrate asynchronous functionality using all the standard Java EE features like JPA and transactions into enterprise applications. I would say the waiting was worthwhile.
Example source code can be found on github.
ava EE 7 - Injection into Runnable/Callable object ejb entityManager Concurrency ManagedExecutorService 异步调用如何获取context的更多相关文章
- java 多线程实现四种方式解析Thread,Runnable,Callable,ServiceExcutor,Synchronized ,ReentrantLock
		
1.Thread实现: import java.util.Date; import java.text.SimpleDateFormat; public class MyThread extends ...
 - callable object与新增的function相关   C++11中万能的可调用类型声明std::function<...>
		
在c++11中,一个callable object(可调用对象)可以是函数指针.lambda表达式.重载()的某类对象.bind包裹的某对象等等,有时需要统一管理一些这几类对象,新增的function ...
 - callable(object)
		
callable(object) 中文说明:检查对象object是否可调用.如果返回True,object仍然可能调用失败:但如果返回False,调用对象ojbect绝对不会成功. 注意:类是可调用的 ...
 - SpringMVC异步调用,Callable和DeferredResult的使用
		
Callable和DeferredResult都是springMVC里面的异步调用,Callable主要用来处理一些简单的逻辑,DeferredResult主要用于处理一些复杂逻辑 1.Callabl ...
 - object C—类中函数的调用
		
Object C-类中函数的调用 创建,三个类.然后,在代码中调用相同名字的函数.观察他们的调用次序. @interface test : NSObject - (void)print; @end @ ...
 - 使用Callable或DeferredResult实现springmvc的异步请求
		
使用Callable实现springmvc的异步请求 如果一个请求中的某些操作耗时很长,会一直占用线程.这样的请求多了,可能造成线程池被占满,新请求无法执行的情况.这时,可以考虑使用异步请求,即主线程 ...
 - 内置函数callable(object)
		
如果对象object参数是可以调用的对象,就返回True:否则返回False.不过要注意的是,当一个对象是可以调用的,并不表示调用该对象时执行一定成功,但不可调用的对象去调用时一定不会成功.如果类对象 ...
 - java并发编程--Runnable  Callable及Future
		
1.Runnable Runnable是个接口,使用很简单: 1. 实现该接口并重写run方法 2. 利用该类的对象创建线程 3. 线程启动时就会自动调用该对象的run方法 通常在开发中结合Execu ...
 - Java 多线程 socket 取款例子  runnable callable
		
socket部分参考 http://blog.csdn.net/kongxx/article/details/7259465 取款部分参考 http://blog.csdn.net/dayday198 ...
 
随机推荐
- Oracle创建'数据库'三步走
			
--创建表空间 create tablespace waterboss datafile 'd:\waterboss.dbf' size 100m autoextend on next 10m; -- ...
 - Oracle查询数据库编码
			
select userenv('language') from dual
 - fatal: HttpRequestException encountered解决方法
			
最近在windows下git push提交就会弹出如下错误: 网上查了一下发现是Github 禁用了TLS v1.0 and v1.1,必须更新Windows的git凭证管理器,才行. https:/ ...
 - C# Note18: 使用wpf制作about dialog(关于对话框)
			
前言 基本上任何software或application都会在help菜单中,有着一个关于对话框,介绍产品的版权.版本等信息,还有就是对第三方的引用(add author credits). 首先,看 ...
 - keyvalue对RDD s
			
scala> val input =sc.textFile("/home/simon/SparkWorkspace/test.txt")input: org.apache.s ...
 - bootstrap.css.map 404
			
删除bootstrap.css的最后一行即可: /*# sourceMappingURL=bootstrap.css.map */ English: from bootstrap-theme.css ...
 - WPF设置软件界面背景为MediaElement并播放视频
			
在我们的常见的软件界面设计中我们经常会设置软件的背景为SolidColorBrush或者LinerColorBrush.RadialGradientBrush 等一系列的颜色画刷为背景,有时我们也会使 ...
 - JavaScript之简易http接口测试工具网页版
			
简易http接口测试工具网页版,支持get.post请求,支持json格式消息体,form表单暂不支持. httpClient.html <!DOCTYPE html> <html ...
 - Java多线程之线程状态转换图
			
说明:线程共包括以下5种状态.1. 新建状态(New) : 线程对象被创建后,就进入了新建状态.例如,Thread thread = new Thread().2. 就绪状态(Runn ...
 - 11/5/2018模拟 Problem C
			
题面 题解 我有特殊的哈希技巧 以到下一个相同字符的距离为值哈希, 如果不存在或在串外, 就是 \(|T| + 1\). 加入一个新字符 \(S_i\) 时, 同时修改它上一次出现时的值, 由 \(| ...