adam bien's blog

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 !