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