多线程专家

IO密集型的线程池大小设置

2017-07-18  本文已影响1068人  go4it

类型判断(CPU密集orIO密集or混合型)

看应用是CPU密集型的还是IO密集型的,还是混合型的。

IO密集型线程大小

/**
 * Support class for thread pool size
 * 
 * @author Nadeem Mohammad
 *
 */
public final class ThreadPoolUtil {
    
    private ThreadPoolUtil() {
        
    }
    /**
     * Each tasks blocks 90% of the time, and works only 10% of its
     *  lifetime. That is, I/O intensive pool
     * @return io intesive Thread pool size
     */
    public static int ioIntesivePoolSize() {
        
        double blockingCoefficient = 0.9;
        return poolSize(blockingCoefficient);
    }

    /**
     * 
     * Number of threads = Number of Available Cores / (1 - Blocking
     * Coefficient) where the blocking coefficient is between 0 and 1.
     * 
     * A computation-intensive task has a blocking coefficient of 0, whereas an
     * IO-intensive task has a value close to 1,
     * so we don't have to worry about the value reaching 1.
     *  @param blockingCoefficient the coefficient
     *  @return Thread pool size
     */
    public static int poolSize(double blockingCoefficient) {
        int numberOfCores = Runtime.getRuntime().availableProcessors();
        int poolSize = (int) (numberOfCores / (1 - blockingCoefficient));
        return poolSize;
    }
}

使用

ExecutorService executorService = Executors.newFixedThreadPool(ThreadPoolUtil.ioIntesivePoolSize());

这样语义化设置,表达能力强一些。

doc

上一篇下一篇

猜你喜欢

热点阅读