2017-05-05 19 views
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()

+0

簡而言之,沒有什麼可以做的。不響應中斷的代碼是流氓代碼。你不能強迫它停下來。 – VGR

回答

0

Future.cancel調用不會終止正在進行的過程。這更像是未來任務的暗示,這個任務被取消了。除此之外,沒有保證從第三方庫中停止Thread的方法。你唯一能夠希望的是迭代ThreadGroup並且在它們上面調用interrupt(),然後希望正在進行的Thread具有對isInterrupted的處理並且取消自己。

相關問題