Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;
//License from project: Open Source License 

import java.util.concurrent.ExecutorService;

import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class Main {
    private static final int NUM_CPU = Runtime.getRuntime().availableProcessors();

    /**
     * @return an {@link ExecutorService} with One worker thread for each CPUm A {@link SynchronousQueue} and a {@link ThreadPoolExecutor.CallerRunsPolicy}
     */
    public static ExecutorService getTightThreadPool() {
        return getTightThreadPool(1d);
    }

    /**
     * @param threadToCpuRatio - for example, assuming you have 2 CPUs and setting a threadToCpuRation to 3, the result will be a pool with 6 working threads.  
     * @return an {@link ExecutorService} with defined amount of worker thread for each CPUm A {@link SynchronousQueue} and a {@link ThreadPoolExecutor.CallerRunsPolicy}
     */
    public static ExecutorService getTightThreadPool(double threadToCpuRatio) {
        int workingThreads = Double.valueOf(NUM_CPU * threadToCpuRatio).intValue();
        return new ThreadPoolExecutor(workingThreads, workingThreads, 60, TimeUnit.SECONDS,
                new SynchronousQueue<Runnable>(true), new ThreadPoolExecutor.CallerRunsPolicy());
    }
}