Jboss Java EE container and an ExecutorService

后端 未结 5 1768
滥情空心
滥情空心 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:28

    The correct way to do this in your EJB is to use the ManagedExecutorService, which is part of the Concurrency Utils API (Java EE7). You shouldn't be using any ExecutorService that is part of the java.util.concurrent in your enterprise code.

    By using the ManagedExecutorService your new thread will be created and managed by the container.

    The following example is taken from my site here.

    To create a new thread using a ManagedExecutorService, first create a task object that implements Callable. Within the call() method we will define the work that we want carried out in a separate thread.

    public class ReportTask implements Callable {
    
        Logger logger = Logger.getLogger(getClass().getSimpleName());
    
        public Report call() {
            try {
                Thread.sleep(3000);
            catch (InterruptedException e) {
                logger.log(Level.SEVERE, "Thread interrupted", e);
            }
            return new Report();
        }
    }
    

    Then we need to invoke the task by passing it though to the submit() method of the ManagedExecutorService.

    @Stateless
    public class ReportBean {
    
        @Resource
        private ManagedExecutorService executorService;
    
        public void runReports() {
            ReportTask reportTask = new ReportTask();
            Future future = executorService.submit(reportTask);
        }
    }
    

提交回复
热议问题