05 - Asynchronous Method Invocation in EJB

 

EJB3 Session beans provide a way to execute long running methods in asynchronous mode using the annotation @Asynchronous and also provide a way to track and cancel the asynchronous execution of the methods using the JavaSE concurrency API.

Example:

@Asynchronous
public void longRunningMethod() {

}

Now, once the longRunningMethod () is invoked, your thread won’t be blocked until the execution of the method finishes.

As the method return type is void, you have 2 choices here, to use void, or to use Future<X>, where X is expected return type of the method in future.

As an example:

@Asynchronous
public Future<String> longRunningMethod() {
    return new AsyncResult<String>("Some Status");
}

You can use the return object from the method to track the method execution status (done, canceled...etc) and to get the return value of the method or to cancel the process execution.

The rules and behaviors applied to the JavaSE concurrency API related to the Future interface are valid here also.

Remote Interface vs Local Interface

As you have seen in the previous examples for creating EJBs, an EJB may have Remote interface and Local Interface. In this section we will see the difference between both interfaces and understand when to use each interface.

Local Interfaces are used to access the EJB object that resides in the same container as the client object, but the Remote Interfaces are used to access EJB objects that are contained in another container and on another JVM other than the client JVM.

In Local Interfaces (View), method parameters are passed by reference, but in Remote View, method parameters are passed by value, copied from client to server and EJB return value is also copied from server to client.

Remote Interfaces can be used to cluster EJB objects.

Like us on Facebook