The asynchronous annotation

The simplest thing to make an EJB asynchronous is through the @Asynchronous annotation. If a client calls an EJB marked with this annotation, it must not wait for the result because all the operations of the EJB will work in asynchronous mode. Here's a sample of an asynchronous singleton EJB:

@Singleton
@Asynchronous
public class AsyncBean {
private static final Logger logger = ...

public void ignoreResult(int a, int b) {
logger.info("it's asynchronous");
// here you can add an heavy payload!
}

public Future<Integer> longProcessing(int a, int b) {
return new AsyncResult<Integer>(a * b);
}
}

In this example, we have two methods--one void and one returning a result. The ignoreResult method will be executed in a few milliseconds despite a large amount of data being loaded. All the loading will be executed in an asynchronous mode.

The longProcessing method returns a javax.ejb.AsyncResult class. This class is a simple implementation of typed Future class that we saw in Chapter 5, Working with Distributed Transactions. This class wraps the real result.

Let's see how a generic client calls these methods:

...
@Inject
private AsyncBean asyncBean;
...
asyncBean.ignoreResult(0, 0);
...
Future<Integer> futureResult = asyncBean.longProcessing(8, 9);
Integer intResult = futureResult.get();

When a client thread receives a value, it needs to do a synchronous call until the value is not received. This operation is done when the get() method of the futureResult object is called. So, try not to increase the wait time when you execute the get call.

In the preceding example, we have a whole asynchronous class; all its methods are asynchronous. The @Asynchronous annotation can mark methods as well, in order to have both synchronous and asynchronous methods in our class.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.225.10.116