/** Demonstrate how to handle an Exception from an asynchronous call. */ private void callAsyncWithFailure() throws InterruptedException { Future<String> x; try { x = accessBean .failure(); // this method will return successfully, because the invocation will be // successful! } catch (IllegalAccessException e) { throw new RuntimeException("Unexpected failure during start asynchronous execution!", e); } try { x.get(); // this will not return successfully } catch (ExecutionException e) { // the IllegalAccessException is thrown by the bean method if (e.getCause() instanceof IllegalAccessException) { // This is the expected behavior LOGGER.info("Catch the expected Exception of the asynchronous execution!"); } else if (e.getCause().getCause() instanceof IllegalAccessException) { LOGGER.info( "Catch the covered Exception of the asynchronous execution, you may be using an older release of JBoss EAP!"); } else { throw new RuntimeException("Unexpected ExecutionException during asynchronous call!", e); } } }
/** * Demonstrate a fire-and-forget call to an asynchronous bean. * * @throws InterruptedException */ private void fireAndForget() throws InterruptedException { long sleepMillis = 15000; accessBean.fireAndForget(sleepMillis); LOGGER.info( String.format( "The server log should contain a message at (about) %s, indicating that the call to the asynchronous bean completed.", new Date(new Date().getTime() + sleepMillis))); }
/** * Demonstrate how to call an asynchronous EJB and continue local work meanwhile. After finishing * local work wait for the result of the server call.<br> * Remember that the call of Future.get() will have a remote roundtrip to the server. */ private void waitForAsyncResult() throws InterruptedException, ExecutionException, TimeoutException { Future<String> myResult = accessBean.longerRunning(1500); // Start a call with a short duration // you might do something here // get() without a timeout will wait until the remote result is present. LOGGER.info("Got the async result as expected after wait => " + myResult.get()); }
/** * Demonstrate how to call an asynchronous EJB, and then perform another task whilst waiting for * the result. If the result is not present after the timeout of get(<timeout>) the result will be * ignored. * * @throws TimeoutException Will be thrown if you change the timing */ private void getResultAsync() throws InterruptedException, ExecutionException, TimeoutException { Future<String> myResult = accessBean.longerRunning(200); // Start a call with a short duration // simulate something // wait below 200ms will force a timeout during get Thread.sleep(400); // If you handle the TimeoutException you are able to ignore the result // WARNING: there might be an ERROR at server side that the result is not delivered LOGGER.info("Got the async result as expected => " + myResult.get(1, TimeUnit.MILLISECONDS)); }