How to do it...

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

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 + '}';
}
}
  1. 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);
}
}
}
  1. Now we create a simple Callable task to communicate with the slow bean:
@Stateless
public class AsyncTask implements Callable<User>{

@Override
public User call() throws Exception {
return new UserBean().getUser();
}

}
  1. Here, we call our proxy:
@Singleton
public class ExecutorProxy {

@Resource(name = "LocalManagedThreadFactory")
private ManagedThreadFactory factory;

@Resource(name = "LocalContextService")
private ContextService context;

private ExecutorService executor;

@PostConstruct
public void init(){
executor = new ThreadPoolExecutor(1, 5, 10,
TimeUnit.SECONDS, new ArrayBlockingQueue<>(5),
factory);
}

public Future<User> submit(Callable<User> task){
Callable<User> ctxProxy =
context.createContextualProxy(task, Callable.class);
return executor.submit(ctxProxy);
}
}
  1. And finally, we create the endpoint that will use the proxy:
@Stateless
@Path("asyncService")
public class AsyncService {

@Inject
private ExecutorProxy executor;

@GET
public void asyncService(@Suspended AsyncResponse response)
{
Future<User> result = executor.submit(new AsyncTask());
response.resume(Response.ok(result).build());
}

}

To try this code, just deploy it to GlassFish 5 and open this URL:

http://localhost:8080/ch09-proxy-task/asyncService

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

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