有没有一种标准的很好的方式来在Java中调用一个阻塞方法并且超时?我希望能够做到:如何在Java中使用超时调用某种阻塞方法?
// call something.blockingMethod();
// if it hasn't come back within 2 seconds, forget it
如果这是有道理的。
谢谢。
有没有一种标准的很好的方式来在Java中调用一个阻塞方法并且超时?我希望能够做到:如何在Java中使用超时调用某种阻塞方法?
// call something.blockingMethod();
// if it hasn't come back within 2 seconds, forget it
如果这是有道理的。
谢谢。
你可以使用一个执行人:
ExecutorService executor = Executors.newCachedThreadPool();
Callable<Object> task = new Callable<Object>() {
public Object call() {
return something.blockingMethod();
}
};
Future<Object> future = executor.submit(task);
try {
Object result = future.get(5, TimeUnit.SECONDS);
} catch (TimeoutException ex) {
// handle the timeout
} catch (InterruptedException e) {
// handle the interrupts
} catch (ExecutionException e) {
// handle other exceptions
} finally {
future.cancel(true); // may or may not desire this
}
如果future.get
没有在5秒钟内返回,它抛出一个TimeoutException
。超时时间可配置为秒,分钟,毫秒或TimeUnit
中的常数单位。
查看JavaDoc了解更多详情。
您可以将呼叫包装在FutureTask
中,并使用get()的超时版本。
见http://java.sun.com/j2se/1.5.0/docs/api/java/util/concurrent/FutureTask.html
FutureTask ISN “上的任务放置时间限制””。 t本身是异步的,是吗?就其本身而言,它只是同步地做事情,你需要将它与Executor结合起来,以实现异步行为。 – skaffman 2009-07-22 10:30:48
是的,你需要一个像你编码的执行者 – 2009-07-22 11:40:01
Thread thread = new Thread(new Runnable() {
public void run() {
something.blockingMethod();
}
});
thread.start();
thread.join(2000);
if (thread.isAlive()) {
thread.stop();
}
注意,该站已被弃用,更好的选择是设置一些挥发性布尔标志,里面blockingMethod()检查并退出,就像这样:
import org.junit.*;
import java.util.*;
import junit.framework.TestCase;
public class ThreadTest extends TestCase {
static class Something implements Runnable {
private volatile boolean stopRequested;
private final int steps;
private final long waitPerStep;
public Something(int steps, long waitPerStep) {
this.steps = steps;
this.waitPerStep = waitPerStep;
}
@Override
public void run() {
blockingMethod();
}
public void blockingMethod() {
try {
for (int i = 0; i < steps && !stopRequested; i++) {
doALittleBit();
}
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
public void doALittleBit() throws InterruptedException {
Thread.sleep(waitPerStep);
}
public void setStopRequested(boolean stopRequested) {
this.stopRequested = stopRequested;
}
}
@Test
public void test() throws InterruptedException {
final Something somethingRunnable = new Something(5, 1000);
Thread thread = new Thread(somethingRunnable);
thread.start();
thread.join(2000);
if (thread.isAlive()) {
somethingRunnable.setStopRequested(true);
thread.join(2000);
assertFalse(thread.isAlive());
} else {
fail("Exptected to be alive (5 * 1000 > 2000)");
}
}
}
又见番石榴的TimeLimiter其使用执行者在幕后。
假设blockingMethod
只是休眠一段米利斯:
public void blockingMethod(Object input) {
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
我的解决方案是使用wait()
和这样的:
public void blockingMethod(final Object input, long millis) {
final Object lock = new Object();
new Thread(new Runnable() {
@Override
public void run() {
blockingMethod(input);
synchronized (lock) {
lock.notify();
}
}
}).start();
synchronized (lock) {
try {
// Wait for specific millis and release the lock.
// If blockingMethod is done during waiting time, it will wake
// me up and give me the lock, and I will finish directly.
// Otherwise, when the waiting time is over and the
// blockingMethod is still
// running, I will reacquire the lock and finish.
lock.wait(millis);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
,这样你们可以取代
something.blockingMethod(input)
到
something.blockingMethod(input, 2000)
希望它有帮助。
对于jcabi-aspects库,还有一个AspectJ解决方案。
@Timeable(limit = 30, unit = TimeUnit.MINUTES)
public Soup cookSoup() {
// Cook soup, but for no more than 30 minutes (throw and exception if it takes any longer
}
它不能得到更简洁,但是您必须依赖AspectJ并将它引入您的构建生命周期当然。
有文章进一步解释它:Limit Java Method Execution Time
你需要一个circuit breaker实现像在GitHub上failsafe项目的一个存在。
试试这个。更简单的解决方案保证如果在时限内没有执行阻止。该进程将终止并引发异常。
public class TimeoutBlock {
private final long timeoutMilliSeconds;
private long timeoutInteval=100;
public TimeoutBlock(long timeoutMilliSeconds){
this.timeoutMilliSeconds=timeoutMilliSeconds;
}
public void addBlock(Runnable runnable) throws Throwable{
long collectIntervals=0;
Thread timeoutWorker=new Thread(runnable);
timeoutWorker.start();
do{
if(collectIntervals>=this.timeoutMilliSeconds){
timeoutWorker.stop();
throw new Exception("<<<<<<<<<<****>>>>>>>>>>> Timeout Block Execution Time Exceeded In "+timeoutMilliSeconds+" Milli Seconds. Thread Block Terminated.");
}
collectIntervals+=timeoutInteval;
Thread.sleep(timeoutInteval);
}while(timeoutWorker.isAlive());
System.out.println("<<<<<<<<<<####>>>>>>>>>>> Timeout Block Executed Within "+collectIntervals+" Milli Seconds.");
}
/**
* @return the timeoutInteval
*/
public long getTimeoutInteval() {
return timeoutInteval;
}
/**
* @param timeoutInteval the timeoutInteval to set
*/
public void setTimeoutInteval(long timeoutInteval) {
this.timeoutInteval = timeoutInteval;
}
}
例如:
try {
TimeoutBlock timeoutBlock = new TimeoutBlock(10 * 60 * 1000);//set timeout in milliseconds
Runnable block=new Runnable() {
@Override
public void run() {
//TO DO write block of code
}
};
timeoutBlock.addBlock(block);// execute the runnable block
} catch (Throwable e) {
//catch the exception here . Which is block didn't execute within the time limit
}
作为参考,由布赖恩戈茨PP检查出的Java并发实践126 - 134,具体而言截面6.3.7 – 2014-12-04 22:57:43