Injecting An ExecutorService With Java EE 7


import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import javax.annotation.Resource;
import javax.ejb.Stateless;
import javax.enterprise.concurrent.ManagedExecutorService;

@Stateless
public class Threader {

    @Resource
    private ManagedExecutorService mes;


    public String computeAnswer() {
        Callable theAnswer = new Callable() {

            @Override
            public String call() throws Exception {
                //the computation is usually expensive
                return "42";
            }
        };
        Future futureResult = mes.submit(theAnswer);
        try {
            return futureResult.get();
        } catch (InterruptedException | ExecutionException ex) {
            throw new IllegalStateException("Cannot get the answer", ex);
        }
    }
}

The JSR-236 "Concurrency Utilities for Java EE" specification comes with Java EE 7 and defines injectable thread factories, executors and support classes for deeper integration between POJOs and Java EE.

For Java EE 6, see: http://connectorz.adam-bien.com

See you at Java EE Workshops at MUC Airport, especially in Effective Java EE and Java EE Architectures !

Comments:

Hi Adam,
it is not clear to me: when it is better to use @Asynchronous and when should I use JSR-236 ExecutorService instead? It seems to me that using directly an ExecutorService in a J2EE env is a return to a more complicated solution already proposed but avoided in the past to run an async task.
There is any suggested pattern of usage?
Thanks

Posted by Matteo on June 25, 2013 at 03:31 PM CEST #

Where do I configure that executor service?

I like the question about when to use @Asynchronous and and when to use the executor service.

Posted by Thai on July 02, 2013 at 07:46 PM CEST #

@Matteo @Thai,

Good answer from the below link:

https://developer.jboss.org/message/851027#851027

Posted by nlloyd on February 19, 2016 at 04:30 PM CET #

Post a Comment:
  • HTML Syntax: NOT allowed
...the last 150 posts
...the last 10 comments
License