- Let's first create a User POJO:
public class User {
private Long id;
private String name;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public User(Long id, String name) {
this.id = id;
this.name = name;
}
@Override
public String toString() {
return "User{" + "id=" + id + ",
name=" + name + '}';
}
}
- And then, we create a slow bean to return User:
public class UserBean {
public User getUser(){
try {
TimeUnit.SECONDS.sleep(5);
long id = new Date().getTime();
return new User(id, "User " + id);
} catch (InterruptedException ex) {
long id = new Date().getTime();
return new User(id, "Error " + id);
}
}
}
- Now we create a simple Callable task to communicate with the bean:
public class AsyncTask implements Callable<User> {
private final UserBean userBean =
CDI.current().select(UserBean.class).get();
@Override
public User call() throws Exception {
return userBean.getUser();
}
}
- And finally, we create our service to schedule and write the task's result in the response:
@Stateless
@Path("asyncService")
public class AsyncService {
@Resource(name = "LocalManagedScheduledExecutorService")
private ManagedScheduledExecutorService executor;
@GET
public void asyncService(@Suspended AsyncResponse response) {
ScheduledFuture<User> result = executor.schedule
(new AsyncTask(), 5, TimeUnit.SECONDS);
while (!result.isDone()) {
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException ex) {
System.err.println(ex.getMessage());
}
}
try {
response.resume(Response.ok(result.get()).build());
} catch (InterruptedException | ExecutionException ex) {
System.err.println(ex.getMessage());
response.resume(Response.status(Response.Status
.INTERNAL_SERVER_ERROR).entity(ex.getMessage())
.build());
}
}
}
To try this code, just deploy it to GlassFish 5 and open this URL:
http://localhost:8080/ch09-scheduled-task/asyncService