Multithreading in a stateless session bean?

后端 未结 4 2109
梦如初夏
梦如初夏 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:29

    In my simplified understanding, it's like running a company. You're the boss (the container), and there's an employee which suddenly just hire 100 people out of the blue without any notice (the bean).

    But you can still easily do multithreading with the @Asynchronous annotation (there are other ways too).

    @Stateless
    public class Employee {
        @Asynchronous
        public Future work(Project projectThatTakeTooLong) {
            // work work work
            return new AsyncResult(null);
        }
    }
    
    @Stateless
    public class Boss {
    
        @Inject
        private Employee randomStatelessEmployee;
    
        public void giveWork() {
            Future result1 = randomStatelessEmployee.work(new Project());
            Future result2 = randomStatelessEmployee.work(new Project());
            Future result3 = randomStatelessEmployee.work(new Project());
            result1.get();
            result2.get();
            result3.get();
        }
    }
    

    There's also a better example here: Jboss Java EE container and an ExecutorService

提交回复
热议问题