How it works...

All the magic relies on the AsyncService class, so we will focus on that.

First, we ask the server an instance of an executor:

    @Resource(name = "LocalManagedScheduledExecutorService")    private ManagedScheduledExecutorService executor;

But it is not just any executor—it's an executor that's specific to scheduling:

ScheduledFuture<User> result = executor.schedule(new AsyncTask(), 5, TimeUnit.SECONDS);

So, we are scheduling our task to be executed in five seconds. Note that we are also not using a regular Future, but ScheduledFuture.

The rest is a usual task execution:

        while (!result.isDone()) {            try {                TimeUnit.SECONDS.sleep(1);            } catch (InterruptedException ex) {                System.err.println(ex.getMessage());            }        }

And this is how we write ...

Get Java EE 8 Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.