IO密集型的線程池大小設置

類型判斷(CPU密集orIO密集or混合型)

看應用是CPU密集型的仍是IO密集型的,仍是混合型的。segmentfault

  • CPU密集
    CPU密集型的話,通常配置CPU處理器個數+/-1個線程,所謂CPU密集型就是指系統大部分時間是在作程序正常的計算任務,例如數字運算、賦值、分配內存、內存拷貝、循環、查找、排序等,這些處理都須要CPU來完成。線程

  • IO密集
    IO密集型的話,是指系統大部分時間在跟I/O交互,而這個時間線程不會佔用CPU來處理,即在這個時間範圍內,能夠由其餘線程來使用CPU,於是能夠多配置一些線程。code

  • 混合型
    混合型的話,是指二者都佔有必定的時間。排序

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

相關文章
相關標籤/搜索