2017-05-05 2 views
0

에서 정지 방법 exection을 강제로 어떻게하는 방법이있다. 호출 가능 <Object> 호출 방법

내가 시도 :

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() 메서드의 현재 스레드에 isInterrupted()을 추가 할 수 없습니다.

+0

간단히 말해서, 할 수있는 일이 없습니다. 인터럽트에 응답하지 않는 코드는 사기성 코드입니다. 강제로 멈출 수는 없습니다. – VGR

답변

0

Future.cancel 호출은 진행중인 프로세스를 종료하지 않습니다. 이 작업이 취소 된 향후 작업에 대한 힌트와 비슷합니다. 그 외에도 제 3 자 라이브러리에서 Thread을 중지 할 수있는 보장 된 방법이 없습니다. 당신이 바라는 유일한 방법은 ThreadGroup을 반복하고 그들에 interrupt()을 부르고 희망으로 진행중인 ThreadisInterrupted에 대한 처리가 있고 스스로 취소한다는 것입니다.