美文网首页
java线程池使用注意事项

java线程池使用注意事项

作者: 摸摸脸上的胡渣 | 来源:发表于2020-02-08 21:06 被阅读0次

1.慎用FixedThreadPool

看一下FixedThreadPool的构造方法

/**
     * Creates a thread pool that reuses a fixed number of threads
     * operating off a shared unbounded queue.  At any point, at most
     * {@code nThreads} threads will be active processing tasks.
     * If additional tasks are submitted when all threads are active,
     * they will wait in the queue until a thread is available.
     * If any thread terminates due to a failure during execution
     * prior to shutdown, a new one will take its place if needed to
     * execute subsequent tasks.  The threads in the pool will exist
     * until it is explicitly {@link ExecutorService#shutdown shutdown}.
     *
     * @param nThreads the number of threads in the pool
     * @return the newly created thread pool
     * @throws IllegalArgumentException if {@code nThreads <= 0}
     */
    public static ExecutorService newFixedThreadPool(int nThreads) {
        return new ThreadPoolExecutor(nThreads, nThreads,
                                      0L, TimeUnit.MILLISECONDS,
                                      new LinkedBlockingQueue<Runnable>());
    }

注意最后一行的LinkedBlockingQueue,这是一个无界队列,如果消费能力跟不上,那么就会在这个无界队列中无限制的增加task,内存就会被打爆,妥妥的让你写casestudy外加diss code reviewer。

顺便看下Alibaba命名规范中对线程池使用的要求
【强制】线程池不允许使用 Executors 去创建,而是通过 ThreadPoolExecutor的方式,这样 的处理方式让写的同学更加明确线程池的运行规则,规避资源耗尽的风险。 说明: Executors 返回的线程池对象的弊端如下: 1) FixedThreadPool 和 SingleThreadPool : 允许的请求队列长度为 Integer.MAX_VALUE ,可能会堆积大量的请求,从而导致 OOM 。 2) CachedThreadPool 和 ScheduledThreadPool : 允许的创建线程数量为 Integer.MAX_VALUE ,可能会创建大量的线程,从而导致 OOM 。

相关文章

  • 线程

    Java 并发编程:线程池的使用 Java 并发编程:线程池的使用java 多线程核心技术梳理 (附源码) 本文对...

  • Java线程池解析

    参考文章:Java并发:线程池,饱和策略 前言 Java线程池的使用在工作中还是比较常见的,线程池可以减小线程建立...

  • 零碎知识点整理

    sofa结构体系:多模块 sofa中使用sofa线程池 Java 线程池的使用非常广泛,目前有两类广泛使用的线程池...

  • 线程池

    线程池 原创 无尘粉笔 粉笔社区 昨天 Java线程池的Executors的使用 Java通过Executors提...

  • Java/Android中的线程池,看这一篇就够了!(超详细)

    一、为何要使用线程池 在Java中,要使用多线程,除了使用new Thread()之外,还可以使用线程池Execu...

  • springboot线程池创建及使用

    springboot启动类(Application.java)中配置线程池大小 使用类中注入线程池并使用

  • Java并发编程:线程池的使用

    Java并发编程:线程池的使用

  • Java 线程池

    Java线程池是java cocurrent包下提供的类,使用非常方便。本文希望整理下Java 线程池相关的知识以...

  • java 线程池

    java 线程池 Java 的 concurrent 包下提供了多种线程池的实现,使用起来非常方便 Executo...

  • Java线程池总结

    本篇文章讲述Java中的线程池问题,同样适用于Android中的线程池使用。本篇文章参考:Java线程池分析,Ja...

网友评论

      本文标题:java线程池使用注意事项

      本文链接:https://www.haomeiwen.com/subject/fjfmthtx.html