EJB methods may be marked as annotation @javax.ejb.Asynchronous
to inform the EJB container that they invoke tasks separate to the container invocation Java thread. An asynchronous method returns a void
element or it is Future<V>
, where V
is the value type that is being returned.
Here is an example of a session bean using asynchronous invocation:
@Singleton public class AsyncWebpageDownloader { @Asynchronous @Lock(LockType.READ) public Future<String> fetchWebPage(String url) throws IOException { String data = createReport(url); return new AsyncResult<String>(data); } private String createReport(String url) throws IOException { URLConnection http = new URL("url") .openConnection(); InputStream in = http.getInputStream(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); baos.write( (url+": ").getBytes()); try { byte[] buf = new byte[8192]; int len; while ((len = in.read(buf)) > 0) { baos.write(buf, 0, len); nap(); } baos.close(); } finally { in.close(); } return baos.toString(); } private void nap() { try { Thread.sleep(200); } catch (InterruptedException ignored) { } } }
The EJB AsyncWebpageDownloader
has a single method called fetchWebPage()
that is annotated with @Asynchronous
. We also add a concurrency hint to the container with an annotation @javax.ejb.Lock
, to configure this call point with a reader's lock. The method accepts a URL and downloads a web page from the internet into memory. In order to simulate a long running operation, we add some time delays to the file download inside the I/O loop. At the end of the process, the downloaded content is returned to the caller as Future<String>
instance. The result is stored in a special type javax.ejb.AsyncResult
.
3.17.164.34