How to do it...

  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. And finally, we create the endpoint that will call 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());
}
}
}
..................Content has been hidden....................

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