或者直接把

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
@Resource
ManagedExecutorService 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
@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);
        }
    }
 
    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的更多相关文章

  1. java 多线程实现四种方式解析Thread,Runnable,Callable,ServiceExcutor,Synchronized ,ReentrantLock

    1.Thread实现: import java.util.Date; import java.text.SimpleDateFormat; public class MyThread extends ...

  2. callable object与新增的function相关 C++11中万能的可调用类型声明std::function<...>

    在c++11中,一个callable object(可调用对象)可以是函数指针.lambda表达式.重载()的某类对象.bind包裹的某对象等等,有时需要统一管理一些这几类对象,新增的function ...

  3. callable(object)

    callable(object) 中文说明:检查对象object是否可调用.如果返回True,object仍然可能调用失败:但如果返回False,调用对象ojbect绝对不会成功. 注意:类是可调用的 ...

  4. SpringMVC异步调用,Callable和DeferredResult的使用

    Callable和DeferredResult都是springMVC里面的异步调用,Callable主要用来处理一些简单的逻辑,DeferredResult主要用于处理一些复杂逻辑 1.Callabl ...

  5. object C—类中函数的调用

    Object C-类中函数的调用 创建,三个类.然后,在代码中调用相同名字的函数.观察他们的调用次序. @interface test : NSObject - (void)print; @end @ ...

  6. 使用Callable或DeferredResult实现springmvc的异步请求

    使用Callable实现springmvc的异步请求 如果一个请求中的某些操作耗时很长,会一直占用线程.这样的请求多了,可能造成线程池被占满,新请求无法执行的情况.这时,可以考虑使用异步请求,即主线程 ...

  7. 内置函数callable(object)

    如果对象object参数是可以调用的对象,就返回True:否则返回False.不过要注意的是,当一个对象是可以调用的,并不表示调用该对象时执行一定成功,但不可调用的对象去调用时一定不会成功.如果类对象 ...

  8. java并发编程--Runnable Callable及Future

    1.Runnable Runnable是个接口,使用很简单: 1. 实现该接口并重写run方法 2. 利用该类的对象创建线程 3. 线程启动时就会自动调用该对象的run方法 通常在开发中结合Execu ...

  9. Java 多线程 socket 取款例子 runnable callable

    socket部分参考 http://blog.csdn.net/kongxx/article/details/7259465 取款部分参考 http://blog.csdn.net/dayday198 ...

随机推荐

  1. Spring中RedirectAttributes的用法

    RedirectAttributes 是Spring mvc 3.1版本之后出来的一个功能,专门用于重定向之后还能带参数跳转的的工具类.他有两种带参的方式: 第一种: redirectAttribut ...

  2. AngularJS集合数据遍历显示

    AngularJS集合数据遍历显示 <!DOCTYPE html> <html> <head> <meta charset="UTF-8" ...

  3. Kettle 变量(arg位置参数)

    1.表输入中使用?占位作为kettle转换变量 数据预览: 获取变量数据: 使用?传入变量 需要勾选替换sql语句中的变量,并选则从步骤插入数据中所在步骤 数据预览

  4. composer 下载包慢的解决方法

    方法一: 修改 composer 的全局配置文件(推荐方式) 打开命令行窗口(windows用户)或控制台(Linux.Mac 用户)并执行如下命令: composer config -g repo. ...

  5. Python 构建工具 buildout 的介绍与使用

    来到了新公司上班,首先就是得把自己的环境给搭起来.知乎使用了buildout作为python项目的构建工具. 那么什么是 buildout ? buildout的是一款自动化构建工具.由Zope团队开 ...

  6. mysql将视图数据迁移到表中

    #字段必须完全一样 INSERT into table1(所有字段) select * from data.视图

  7. Lodop打印较大的超出纸张的图片

    ADD_PRINT_IMAGE打印图片时,如果一个图片过大,超出纸张,默认超出部分是不显示的,也不会分页.最近遇到有人利用ADD_PRINT_URL打印图片,说图片自动分了多页,因为这个方法一般是用来 ...

  8. DotNetty 实现 Modbus TCP 系列 (三) Codecs & Handler

    本文已收录至:开源 DotNetty 实现的 Modbus TCP/IP 协议 DotNetty 作为一个半成品,我们不需要关注细节的实现,只需要关注自己的业务即可,所以最主要的就是处理 Codecs ...

  9. hibernate主配置文件中指定session与当前线程绑定

    配置一条属性 <property name="hibernate.current_session_context_class">thread</property& ...

  10. linux用户、文件权限相关命令

    root 现代操作系统一般属于多用户的操作系统,也就是说,同一台机器可以为多个用户建立账户,一般这些用户都是为普通用户,这些普通用户能同时登录这台计算机,计算机对这些用户分配一定的资源. 普通用户在所 ...