Let's say the class MyCoolProcess
has the logic of my app which is needed to be called in it's own thread. We'll create a thread, call it and continue with the application.
This class is a EJB; annotated with @Stateless
Now we have the MyController
class; which is going to call a new thread.
Code:
public class MyController {
@EJB
MyCoolProcess p;
public Response foo() {
Thread t = new Thread() {
public void run() {
p.run();
}
};
t.start();
// continues ...
}
}
@Stateless
public class MyCoolProcess {
public void run() {
// heavy task
}
}
That is working fine; the point is... before that solution I've tried with the Runnable
interface. Which was I wanted at first time. The approach would be:
public class MyController {
@EJB
MyCoolProcess p;
public Response foo() {
Thread t = new Thread(p);
t.start();
// continues ...
}
}
@Stateless
public class MyCoolProcess implements Runnable {
@Override
public void run() {
// heavy task
}
}
That doesn't work. Actually, the server cannot start. Crashes trying to inject the dependencies. I'm not be able to implement the interface Runnable
if I'm a EJB isn't it? WHY
And... is there any way to do the Runnable
way instead the anonymous class?
From the EJB spec:
The enterprise bean must not attempt to manage threads. The enterprise bean must not attempt to start, stop, suspend, or resume a thread, or to change a thread’s priority or name. The enterprise bean must not attempt to manage thread groups.
See Adam's Blog.