Jboss Java EE container and an ExecutorService

后端 未结 5 1773
滥情空心
滥情空心 2020-11-29 01:53

I have a standalone java app which used the ExecutorService to process a number of jobs in parallel

 ExecutorService es = Executors.newFixedThreadPool(10);
<         


        
5条回答
  •  庸人自扰
    2020-11-29 02:23

    Obligatory warning: Creating your own threads in a Java EE app server (even Tomcat) is discouraged as it can be a huge performance issue and in most cases will prevent container functionality, such as JNDI, from working. The new threads won't know which application they belong to, the Thread context classloader will not be set and many other hidden issues.

    Fortunately there is a way to get the Java EE server to manage the thread pool via the Java EE 6 @Asynchronous and this clever design pattern. Portable to any Java EE 6 certified server.

    Create this EJB in your application.

    package org.superbiz;
    
    import javax.ejb.Asynchronous;
    import javax.ejb.EJB;
    import javax.ejb.Stateless;
    import java.util.concurrent.Callable;
    import java.util.concurrent.Executor;
    
    @Stateless(name="Executor")
    public class ExecutorBean implements Executor {
    
        @Asynchronous
        @Override
        public void execute(Runnable command) {
            command.run();
        }
    }
    

    Then you can refer to this bean elsewhere in your application via plain dependency injection (if the referring component is a Servlet, Listener, Filter, other EJB, JSF Managed bean).

    @EJB
    private Executor executor;
    

    Then use the Executor as normal.

    If the component is not another Java EE component, you can lookup the bean via:

    InitialContext initialContext = new InitialContext();
    Executor executor = (Executor) initialContext.lookup("java:module/Executor");
    

提交回复
热议问题