超时缓存线程池的各个线程

时间:2013-04-29 08:51:54

标签: multithreading threadpool

我想在Web应用程序中使用一个线程池,它应该同时支持大量用户(~3000个用户)。我在一个单独的线程中调用Web服务,我正在使用线程池执行。每当Web服务无法发送响应时,线程就会卡住。所以我想在150毫秒后停止/超时。这就是我现在正在做的事情:

自定义主题:

public class RetrieveDocTask implements Runnable {
public void run() {
    //gather variables
    //invoke webservice
}}

执行线程的过滤器:

public class DocFilter implements Filter {
private static ExecutorService executor = Executors.newCachedThreadPool();
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
    RetrieveDocTask task=new RetrieveDocTask();
    executor.execute(task);
}}

我浏览互联网寻求解决方案,但没有一个能为我工作。有些人说使用Future和callable,而有些人则要求创建ThreadPoolExecutor并指定超时。不知道为什么它不起作用。 此外,可以为大量用户使用缓存池执行程序。我是新手,需要尽快实施。

1 个答案:

答案 0 :(得分:0)

确实,未来就是你需要的。假设您的类RetriveDoc实际返回一个字符串。

 private static final class RetrieveDoc implements Callable<String>{
      @Override
      public String call() throws Exception {
          //do some computation and retirieve doc
          return "DocAsString";
      }
 }


 ExecutorService service = Executors.newFixedThreadPool(1);
 Future<String> futureResponse = service.submit(new RetrieveDoc());
 //this will blokc for only 150 milliseconds
 String response = null;
 try{
      response = futureResponse.get(150, TimeUnit.MILLISECONDS);
 } catch(TimeoutException e){
     System.out.println("TimeoutException happended");
 }

 if(response == null){
      //do something
 }
相关问题