2013-04-29 65 views
0

我想在应用程序中使用线程池,该应用程序应该同时支持大量用户(〜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可调用,而有些则要求创建ThreadPoolExecutor并指定超时。不知道为什么它不工作。 另外,为大量用户使用缓存池执行器会好吗?我是新手,需要尽快实施。

回答

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 
} 
+0

对于测试,我放置了String response = futureResponse.get(5,TimeUnit.MINUTES);当我在调用方法中放置一个断点并让它等待超过五分钟时,我期待TimeoutException。但是那没有发生。另外,我是否需要将这两个语句放在一个同步块中。 Future futureResponse = service.submit(new RetrieveDoc()); //这将blokc只有150毫秒 字符串响应= futureResponse.get(150,TimeUnit.MILLISECONDS); – nevin 2013-04-30 05:01:05

+0

@nevin这不会在调试工作。不,那不需要进入同步模块。 – Eugene 2013-04-30 07:18:34

+0

我还有疑问,那就是我当时不接受的原因。我现在已经接受了,但我仍然不确定。 FuturefutureResponse = service.submit(new RetrieveDoc());然后它的暂停和其他一些线程开始在该过滤器上运行。所以下一次该线程有机会调用futureResponse.get时,它将不会很快得到超时异常。 – nevin 2013-04-30 12:28:26