How it works...

If you followed the last recipe, you should already be familiar with the Callable task, so I won't go into detail about it here. Now, we implement our task using both the Callable and ManagedTaskListener interfaces. The latter interface provides us with all the methods for checking the task's status. Consider the following code block:

    @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 these—ManagedExecutorService (explained next) does this for you.

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

@Resource
private ManagedExecutorService executor;

In the service itself, we get four users from our asynchronous task, as follows:

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 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.216.186.164