0
我有一个方法:如何强制停止方法exection从赎回<Object>调用方法
public class Datasource {
public void create() throws MyException{
// can take more time than expected
}
}
我要超时添加到这个方法。
我想:
public class Test {
public static void main(String[] args) throws MyException {
runWithTimeout(new Datasource());
}
public static void runWithTimeout(final Datasource ds) throws MyException {
ExecutorService executor = Executors.newSingleThreadExecutor();
Callable<Object> task = new Callable<Object>() {
public Object call() throws MyException {
ds.create();
return null;
}
};
Future<Object> future = executor.submit(task);
try {
future.get(5, TimeUnit.SECONDS);
} catch (TimeoutException tex) {
throw new MyException("TimeoutException. Caused By", tex);
} catch (InterruptedException iex) {
throw new MyException("InterruptedException. Caused By", iex);
} catch (ExecutionException eex) {
throw new MyException("InterruptedException. Caused By", eex);
} finally {
future.cancel(true);
executor.shutdown();
}
}
}
但create方法仍在运行。我该如何强制阻止它。我不能修改create()
方法。所以我不能在当前线程create()
方法中加isInterrupted()
。
简而言之,没有什么可以做的。不响应中断的代码是流氓代码。你不能强迫它停下来。 – VGR