I'm learning Java EE currently (moving from SE) and I am confused about asynchronous execution in Java EE environment.
Basically what I understand creating Thread
or Timer
is not exactly recommended. One other method what I found so far are use JMS for transfer message to EJB Message Bean and it will be executed asynchronously.
What are some other methods to achieve this behavior? Cause using JMS looks like too much overhead for simple tasks.
The simplest possible solution in Java EE 6 is to use @Asynchronous
annotation on your EJB method (or the whole class). It allows you to invoke a business method asynchronously which means that a new thread will be delegated to execute this method and you'll get the control back in caller method.
In pre-Java EE 6 days the JMS was used for this purpose.
As a side note - in Servlets you can also use asynchronous execution.
You can use the spring task executor.
Other jobs may be putting it in a database and execute a task that is polling the database.
For large applications you could even consider using an Enterprise Service Bus.
It all depends on how important that tasks are and what efforts you are willing to do.
For not so important tasks simple Threads will often do the trick.
The Java EE 6 and Spring enthusiasts have spoken; somehow everyone have left off the javax.ejb.TimerService
from Java EE 5, which, I'll venture a guess, is currently [as of 2011] the predominant platform.
Basically, you inject the TimerService
in your stateless or message-driven bean, and use one of its createTimer(...)
methods to schedule the asynchronous execution. Then you implement the timeout logic in an annotated method:
@Timeout
void anyMethod(javax.ejb.Timer timer) { ... }
And that's that. Using JMS only for the sake of its asynchronous nature has never been a good option, unless as long time ago as in J2EE.
Basically, asynchronous behavior is achieved with threads, there's no getting around that.
However, in a Java EE environment it's considered a bad practice to open threads by yourself. Most likely you'll want to use your server's facility that will give you a (properly) managed environment for doing async stuff.
JMS is one way of doing async tasks, I would recommend that for task streams that need to be continuously processed. Most Java application servers have scheduling managers which allow you to schedule single tasks in the future (e.g. via quartz). Some frameworks also support the Java EE 6 annotations for @javax.ejb.Asynchronous
.
And yes, if you must, you can always just spawn a single Thread
and forget about it all. Just make sure you know what you're doing.
It all boils down to what your exact use-case is, and which methods your environment supports. There's no one single true answer.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With