Java中那些踩過的坑

來源:互聯網
上載者:User

標籤:over   class   scheduled   oid   schedule   筆記   時間   rri   不同   

僅以此隨筆記錄一些在java中踩過而且又重踩的坑 _(:з)∠)_

1. Runnable In ScheduledExecutorsService

 當使用ScheduledExecutorService, Runnable內沒有捕獲的RuntimeException將會使Executor停止運行,並且異常不會被輸出。

     ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor();        scheduler.scheduleAtFixedRate(new Runnable() {            @Override public void run() {                if (Math.random() > 0.5)                    throw new NullPointerException("THROW A NPE HERE");                System.out.println("tick");            }        }, 0, 1, TimeUnit.SECONDS);

 可以試著執行這段代碼,定時任務將在你不知不覺中停止。因此,在使用ScheduledExecutorService時,若需要處理不確定值的輸入(例如解析數字字串、解析時間、拆分字串等),強烈建議用try-catch捕獲異常。

 不同於在普通的方法體裡,在這裡建議使用Exception來而不是特定的Exception。

        ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor();        scheduler.scheduleAtFixedRate(new Runnable() {            @Override public void run() {                try {                    if (Math.random() > 0.5)                        throw new NullPointerException("A NPE HERE");                    System.out.println("tick");                } catch (Exception e) {                     // handle your exception here                }            }        }, 0, 1, TimeUnit.SECONDS);

 

Java中那些踩過的坑

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.