2014-01-09 50 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(); 
}