java线程池的使用

java线程池


使用说明:参照java api doc

https://docs.oracle.com/javase/8/docs/api/

  • java.util.concurrent.ThreadPoolExecutor

    Core and maximum pool sizes
    On-demand construction
    Creating new threads
    Keep-alive times
    Queuing(There are three general strategies for queuing)
    Rejected tasks
    Hook methods
    Queue maintenance
    Finalization

  • java.util.concurrent.ScheduledThreadPoolExecutor


    使用场景:在hikariCP jdbc连接池中使用了3个线程池,如下链接:

    http://blog.csdn.net/buzhidaolvtu/article/details/51050646

    hikariCP中创建了3个线程池:

    class HikariPool:

    private final ThreadPoolExecutor addConnectionExecutor;
    private final ThreadPoolExecutor closeConnectionExecutor;
    private final ScheduledThreadPoolExecutor houseKeepingExecutorService;

    class HikariDataSource实例化时,会创建上面3个线程池,同时向houseKeepingExecutorService提交一个周期执行的任务:

    (1)监测idle timeout的connection,如果存在,使用closeConnectionExecutor关闭连接(由线程池里的线程关闭具体的连接);

    (2)如果连接池里的连接数不足,向连接池里补充connection,使用addConnectionExecutor创建新的连接(由线程池里的线程创建连接);每创建一个connection,并且如果设定了maxLifetime,那么同时就会向houseKeepingExecutorService里添加一个定时任务,如下代码(仅关注红色部分),这个定时任务用于检查这个连接的生命周期,到达生命周期时,这个连接会被关闭掉。注意,这个连接到达最大生命周期时,如果该连接还在被使用,那么连接会被打上Evicted(驱逐)的标记,但是并不会从连接池里移除,在下次取得连接池的连接时,如果恰巧取到这个连接,那么这个连接就会被关闭掉。

       private PoolEntry createPoolEntry()
       {
          try {
             final PoolEntry poolEntry = newPoolEntry();

             final long maxLifetime = config.getMaxLifetime();
             if (maxLifetime > 0) {
                // variance up to 2.5% of the maxlifetime
                final long variance = maxLifetime > 10_000 ? ThreadLocalRandom.current().nextLong( maxLifetime / 40 ) : 0;
                final long lifetime = maxLifetime - variance;
                poolEntry.setFutureEol(houseKeepingExecutorService.schedule(new Runnable() {
                   @Override
                   public void run() {
                      softEvictConnection(poolEntry, "(connection has passed maxLifetime)", false /* not owner */);
                   }
                }, lifetime, MILLISECONDS));

             }

             LOGGER.debug("{} - Added connection {}", poolName, poolEntry.connection);
             return poolEntry;
          }
          catch (Exception e) {
             if (poolState == POOL_NORMAL) {
                LOGGER.debug("{} - Cannot acquire connection from data source", poolName, e);
             }
             return null;
          }
       }





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值