Adam Bien's Weblog

Tuesday Jun 25, 2013

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 !


Special Events: Java 8 with Java EE 7: "More Power with Less Code", 13th October, 2014 and Java EE 7: "Testing and Code Quality", 14th October, 2014

A book about rethinking Java EE Patterns

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 #

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