How to do it...

You will need to perform the following steps to try this recipe:

  1. First, we create a User POJO:
public class User implements Serializable{

private Long id;
private String name;

public User(long id, String name){
this.id = id;
this.name = 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;
}

}
  1. Then, we create our asynchronous session bean:
@Stateless
public class UserBean {

@Asynchronous
public Future<User< getUser(){
long id = new Date().getTime();
User user = new User(id, "User " + id);
return new AsyncResult(user);
}

@Asynchronous
public void doSomeSlowStuff(User user){
try {
TimeUnit.SECONDS.sleep(5);
} catch (InterruptedException ex) {
System.err.println(ex.getMessage());
}
}
}
  1. Finally, we create the endpoint that calls the bean:
@Stateless
@Path("asyncService")
public class AsyncService {

@Inject
private UserBean userBean;

@GET
public void asyncService(@Suspended AsyncResponse response){
try {
Future<User< result = userBean.getUser();

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

response.resume(Response.ok(result.get()).build());
} catch (InterruptedException | ExecutionException ex) {
System.err.println(ex.getMessage());
}
}
}

Now, you can try it out by calling the following URL:

http//localhost:8080/ch10-async-bean/asyncService