Multithreading in a stateless session bean?

后端 未结 4 2152
梦如初夏
梦如初夏 2020-12-14 23:50

The EJB 3.0 specification does not allow a business method of a stateless session bean to create new threads. Why is that? What is wrong with creating additional worker thre

4条回答
  •  心在旅途
    2020-12-15 00:41

    One type of workaround:

    import java.util.concurrent.Executor;
    import javax.ejb.Asynchronous;
    import javax.ejb.Stateless;
    
    @Stateless
    public class TransactionalExecutor implements Executor {
    
        @Override @Asynchronous
        public void execute(Runnable command) {
            command.run();
        }
    }
    

    Now you can use TransactionalExecutor as an executor:

    @Stateless
    public class SlowService {
    
        @Inject
        Executor command;
    
        public void invoke(){
            Runnable command = new Runnable() {
                @Override
                public void run() {
                    // heavy task
                }
            };
            command.execute(command);
        }    
    }
    

提交回复
热议问题