Java中那些踩过的坑

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Java中那些踩过的坑相关的知识,希望对你有一定的参考价值。

仅以此随笔记录一些在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中那些踩过的坑的主要内容,如果未能解决你的问题,请参考以下文章

那些年深度学习所踩过的坑-第一坑

那些年踩过的WebAPI的坑

Fragment全解析系列:那些年踩过的坑

记录那些年我踩过的坑

那些年,接口测试踩过的坑~

那些年踩过的坑