How it works...

If you have been through the last recipe, you will already be familiar with the Callable task, so I won't give you more details about it here. But now, we are implementing our task using both the Callable and ManagedTaskListener interfaces. The second one gives us all the methods for checking the task's status:

    @Override
public void taskSubmitted(Future<?> future,
ManagedExecutorService mes, Object o) {
long mili = new Date().getTime();
LOG.log(Level.INFO, "taskSubmitted: {0} -
Miliseconds since instantiation: {1}",
new Object[]{future, mili - instantiationMili});
}

@Override
public void taskAborted(Future<?> future,
ManagedExecutorService mes, Object o, Throwable thrwbl) {
long mili = new Date().getTime();
LOG.log(Level.INFO, "taskAborted: {0} -
Miliseconds since instantiation: {1}",
new Object[]{future, mili - instantiationMili});
}

@Override
public void taskDone(Future<?> future,
ManagedExecutorService mes, Object o, Throwable thrwbl) {
long mili = new Date().getTime();
LOG.log(Level.INFO, "taskDone: {0} -
Miliseconds since instantiation: {1}",
new Object[]{future, mili - instantiationMili});
}

@Override
public void taskStarting(Future<?> future,
ManagedExecutorService mes, Object o) {
long mili = new Date().getTime();
LOG.log(Level.INFO, "taskStarting: {0} -
Miliseconds since instantiation: {1}",
new Object[]{future, mili - instantiationMili});
}

The best part is that you don't need to call any of them—ManagedExecutorService (explained next) will do it for you.

Finally, we have AsyncService. The first declaration is for our executor:

    @Resource
private ManagedExecutorService executor;

In the service itself, we are getting four users from our asynchronous task:

        List<User> usersFound = new ArrayList<>();
while (i < 4) {
Future<User> result = executor.submit(new AsyncTask());

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

try {
usersFound.add(result.get());
} catch (InterruptedException | ExecutionException ex) {
System.err.println(ex.getMessage());
}

i++;
}

Once it's done, it's written to the asynchronous response:

response.resume(Response.ok(usersFound).build());

Now, if you look at your server log output, there are messages from the ManagedTaskListener interface. 

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

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