2014-01-09 49 views
0

我有一個服務於大量事務的系統。 超時策略僅適用於交易的一部分。Java方法的執行超時策略

這裏完整事務包括一些執行的工作流程,前處理,遠程調用的,後處理等。

例如,

//一些代碼

// START TIMER

嘗試 {

CallInput remoteInput = fInputProcessor.transform(callContext);

CallOutput remoteOutput = fRemoteInvoker.invoke(remoteInput);

TransactionOutput output = fOutputProcessor.transform(remoteOutput);

}

趕上(TimeoutException異常前) {

}

//一些代碼

說的超時是500毫秒。它可能發生在輸入處理,遠程調用或輸出處理期間。

你能列出一些可能的方法來在500ms後產生超時嗎?假設我不能將3個塊分成一個新的線程。

回答

1

您可以使用Guava和使用這樣的代碼:

TimeLimiter limiter = new SimpleTimeLimiter(); 
limiter.callWithTimeout(new Callable<Void>() { 
    public Void call() { 
      CallInput remoteInput = fInputProcessor.transform(callContext); 
      CallOutput remoteOutput = fRemoteInvoker.invoke(remoteInput); 
      TransactionOutput output = fOutputProcessor.transform(remoteOutput); 
    } 
    }, 500, TimeUnit.MILISECONDS, false); 
1

使用java.util.concurrent.Future.get(long, TimeUnit)考慮。

Runnable yourTask = <wrap your work code in a Runnable>; 
Future future = threadpool.submit(yourTask); 
try { 
    Object result = future.get(10, TimeUnit.SECONDS); 
} catch (Exception e) { 
    <handle exception, e.g. TimeoutException> 
} finally { 
    <your closing code> 
} 

下面是創建/銷燬線程池的例子:

import java.util.concurrent.ExecutorService; 
import java.util.concurrent.Executors; 
import java.util.concurrent.Future; 
import java.util.concurrent.TimeUnit; 

private ExecutorService threadpool; 

public void start() { 
    threadpool = Executors.newCachedThreadPool(); 
} 

public void stop() throws InterruptedException { 
    threadpool.shutdown(); 
    if (false == threadpool.awaitTermination(1, TimeUnit.SECONDS)) 
     threadpool.shutdownNow(); 
}