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;
      }
   }





你可能感兴趣的:(知识学习,thread,pool)