2017-08-17 245 views
0

我想限制一個方法在java中的執行時間,我想我的特定方法,如果它在一定的時間內執行然後確定否則它應該會引發異常。限制在java中的方法的執行時間

爲此,我嘗試使用爲:

@Timeable(limit = 1000, unit = TimeUnit.MILLISECONDS) 
public void testMethod(){ 
    try { 
      Thread.sleep(2000); 
      if (Thread.interrupted()) { 
        throw new InterruptedException(); 
      } 
     }catch(InterruptedException e1){ 
      logger.error("failed due to-" + e1, e1.getMessage()); 
      throw new InterruptedException(e1.getMessage()); 
     } catch (Exception e) { 
      logger.error(e.getMessage(), e); 
      throw new Exception(e.getMessage()); 
     } 
} 

爲此,我花了參考範圍: http://www.yegor256.com/2014/06/20/limit-method-execution-time.html

應該行之後拋出異常:

Thread.sleep(2000); 

但是這是我的代碼不會拋出異常。

請幫助缺少的東西。

預先感謝任何其他建議的方法用於相同的目的。

+1

您是否編織了您的課程,如您鏈接到的頁面中所述? –

+0

這樣的註釋工作不是獨立的,而是在具體的環境中。閱讀博客庫,exacly配置和使用方法 –

+0

相應的問題不是很好的重複,但[此答案](https://stackoverflow.com/a/45433655/7598776)可能仍然有幫助 –

回答

0

正如在評論中已經提到的,this solution似乎也適用於您的情況。它看起來像這樣:

public void testMethod() { 
    ForkJoinPool forkJoinPool = new ForkJoinPool(1); 
    try { 
     forkJoinPool.submit(() -> 
     { 
     // replace the following linea with the actual code that should be in this method 
      try { 
       Thread.sleep(2000); 
      } catch (InterruptedException e) {} 
      System.out.println("Job done"); 
     }) 
     // wait for x milliseconds before wait times out and TimeOutException is thrown 
       .get(1000, TimeUnit.MILLISECONDS); 
    } catch (TimeoutException e) { 
     // job not done in your interval 
    } catch (InterruptedException | ExecutionException e) { 
     e.printStackTrace(); 
    } 
} 

由於Thread#sleep需要2秒,這是比在.get(...)出指定1秒的等待時間多,這個方法總是超時在這個例子。

+1

謝謝!它按照你的建議代碼片段按要求工作。 – Vikas

0

這裏是代碼和它的自我解釋:爲了測試的目的,我剛剛寫了一個簡單的方法,只會執行3秒。

import java.util.Timer; 
import java.util.TimerTask; 

class Test { 

    Timer timer; 

    public Test(int seconds) { 
     timer = new Timer(); 
     timer.schedule(new RemindTask(), seconds * 1000); 
    } 

    class RemindTask extends TimerTask { 
     public void run() { 
      System.out.format("Time's up!%n"); 
      System.exit(0); 
      timer.cancel(); 
     } 
    } 

    public static void main(String args[]) { 
     Thread t = new Thread(new Runnable() { 
      @Override 
      public void run() { 
       new Test(3); 
       sum(); 
       System.out.format("Task scheduled.%n"); 
      } 
     }); 
     t.start(); 
    } 

    public static void sum(){ 
     for(int i = 0 ; i < 100 ;i++){ 
      try { 
       Thread.sleep(500); 
      } catch (InterruptedException e) { 
       e.printStackTrace(); 
      } 
      System.out.println(i); 
     } 
    } 
} 
+0

你也可以看到鏈接https://stackoverflow.com/questions/15747277/how-to-make-java-program-exit-after-a-couple-of-seconds –

2

對於您所使用的方法,它是不夠的加@Timeable註解,還需要作爲Weaving Java Binaries描述配置方面編織。

有趣的是,博客文章作者和創作者jcabi-aspects,Yegor Bugayenko自此決定Java annotations are a big mistake

另一種方法是使用CompletableFuture

public void testMethod() { 
    CompletableFuture<Void> future = CompletableFuture.runAsync(() -> { 
     try { 
      Thread.sleep(2000); 
     } catch (InterruptedException e) { 
      Thread.currentThread().interrupt(); 
      throw new RuntimeException("Interrupted", e); 
     } 
    }); 
    try { 
     future.get(1000, TimeUnit.MILLISECONDS); 
    } catch (TimeoutException e) { 
     // Operation timed out. Cancel it and log. 
     future.cancel(true); 
     logger.error("Timed out", e); 
    } catch (InterruptedException e) { 
     // Current thread interrupted while waiting. Cancel operation and log. 
     future.cancel(true); 
     logger.error("Interrupted", e); 
     // Reassert interrupt flag, since exception is not propagated. 
     Thread.currentThread().interrupt(); 
    } catch (ExecutionException e) { 
     logger.error("Operation failed", e.getCause()); 
     // No need to cancel in this case, since the operation has completed. 
    } 
} 

注意,代碼總是一再重申中斷狀態醒目InterruptedException時。請參閱Why invoke Thread.currentThread.interrupt() in a catch InterruptException block?

另請注意,如果操作超時或調用線程中斷,操作將被明確取消,以避免浪費資源。

相關問題