2016-05-08 41 views
1

我有一個Java應用程序,它使用多個線程,這些線程在給定時間後使用ScheduledExecutorService開始。每個小時一個線程開始,做一些工作並正確終止。但有時(例如,當HTTP請求不起作用時)該線程崩潰並且執行程序服務不再啓動這樣的線程。然後我必須退出應用程序(使用Ctrl-C)並重新啓動它。Java - 應用程序在線程崩潰後無法正常工作

崩潰線程是否可能中斷ExecutorService以實例化新線程? 我不想經常檢查應用程序是否仍在運行,因爲它運行在我的Raspberry Pi上,應該24/7運行。

也許你可以幫我找到我的問題的解決方案!

編輯

的ExecutorService也運行在自己的線程。這是怎樣的線程啓動:

@Override 
public void run() { 
    threadFuture = executorService.scheduleAtFixedRate(new IntervalThread(i, p, c, a), 60, 60, TimeUnit.MINUTES); 
} 

這是被稱爲每60分鐘線:如果線程(這使得HTTP請求)chrashed

@Override 
public void run() { 

    try { 
     // do some HTTP request here 
     // if an error occurs, catch it and log the error message 
    } catch (Exception e) { 
     LOGGER.error(e.getMessage()); 
    } 
} 

,整個ExecutorService的不再工作了。如果我發現每一個異常,怎麼可能呢?

+0

了'ExecutorService'初始化和你的'Runnable'類的代碼片段將是有益的。 –

回答

2

你的情況確實有一個解釋,因爲ScheduledThreadPoolExecutor

如果任務的任一執行遇到異常,就會取消後續執行。

雖然你正在執行中try{}catch(Exception)塊整個任務/工作,有這樣的情況,其中Throwable的可能「逃跑」的catch塊:

  1. 某種錯誤(如OutOfMemoryError異常)發生。

  2. 您的日誌記錄代碼LOGGER.error(e.getMessage());在登錄時引發異常。

我建議你將以下修改明白是怎麼回事:

@Override 
public void run() { 
try { 
    try { 
    // do some HTTP request here 
    // if an error occurs, catch it and log the error message 
    } catch (Exception e) { 
    LOGGER.error(e.getMessage()); 
    } 
} catch (Throwable t){ 
    t.printStackTrace(); // this would require redirect output like java -jar my.jar >> error_log.txt 
    // try clean up and exit jvm with System.exit(0); 

}  
+0

謝謝!我希望我能夠找出哪些工作不正確。我只需要谷歌如何創建一個* MANIFEST *文件來正確啓動我的.jar :)) – beeef

相關問題