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 ...
随机推荐
- WebSocket推送
本篇博客只是记录websocket在自己的项目中的应用,只是记录,不做说明(后来替换为GoEasy了). /** * 握手的设置,这其实是为了获取session */ public class Get ...
- js如何复制一个对象?
方法一: 把原来对象的属性遍历一遍,赋给一个新的对象. //深复制对象方法 var cloneObj = function (obj) { var newObj = {}; if (obj insta ...
- Chrome---谷歌浏览器修改用户缓存文件夹 如何设置缓存路径
1.首先我们在电脑上打开chrome浏览器,然后地址栏输入chrome://Version,然后按下回车键,找到个人资料路径一项. 2.接下来我们选中个人资料路径后面所有的信息,右键点击信息后选择“复 ...
- 免费苹果账号(apple id)申请ios证书p12真机调试
HBuilder可以直接打包越狱版的ipa包,但需要越狱手机才能安装,如果需要安装到没越狱的手机安装,需要自己申请ios证书打包. 一般是需要一个付费了的苹果开发者账号才能申请ios证书打包. 这里介 ...
- java中解决小数精度问题
public class TestDouble { public static void main(String[] args) { Double d1 = 0.1; Double d2 = 0.2; ...
- 【纪录】Hash about
backup a easy implement # coding: utf-8 def add(k, v): pass def get(target): pass class LinearMap(ob ...
- 通过view实现rest api接口
Django rest framwork之view 基于Django的View实现Json数据的返回: # _*_ encoding:utf-8 _*_ __author__ = 'LYQ' __da ...
- 关于IWMS中遇到的问题及解决方法
1.生成的文章上传到外网上,但是没一会儿又变成原来的样子? 解决方案:把上传页面对应的template中的.aspx页面也要上传到外网去.
- JavaScript 使用 toJSON 方法格式化日期
toJSON 方法可以将 Date 对象转换为 ISO-8601 标准的字符串:YYYY-MM-DDTHH:mm:ss. sssZ var date = new Date(); // toJSON() ...
- ES6函数增强
函数参数可以拥有默认值.调用函数时,如果没有进行相应的实参传递,参数就会使用默认值.怎么给参数提供默认值呢?很简单,声明函数时候,给形参赋一个值就可以了,这个值就是参数的默认值. // num2拥有默 ...