// Collection of code snippets by Arne Vajhøj 
// (likely posted to comp.os.vms/INFO-VAX, INFO-TPU, MACRO32, eksperten.dk, newz.dk, LinkedIn or other place sometime between 1990 and now) 
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;

public class HT {
    public static long fac(int n) {
        if(n < 2) return 1; else return n * fac(n - 1);
    }
    private static final int NTASKS = 10000;
    private static final int NREP = 100000;
    public static void test(int nthreads) throws InterruptedException, ExecutionException {
        long t1 = System.currentTimeMillis();
        ExecutorService es = Executors.newFixedThreadPool(nthreads);
        @SuppressWarnings("unchecked")
        Future<Void>[] res = new Future[NTASKS];
        for(int i = 0; i < NTASKS; i++) {
            res[i] = es.submit(new Callable<Void>() {
                @Override
                public Void call() throws InterruptedException {
                    for(int i = 0; i < NREP; i++) {
                        fac(20);
                    }
                    return null;
                }
            });
        }
        for(int i = 0; i < NTASKS; i++) {
            res[i].get();
        }
        es.shutdown();
        long t2 = System.currentTimeMillis();
        System.out.printf("%d threads : %.3f seconds\n", nthreads, (t2 - t1) / 1000.0);
        
    }
    public static void main(String[] args) throws InterruptedException, ExecutionException {
        test(1);
        test(2);
        test(4);
        test(8);
        test(16);
        test(32);
        test(64);
    }
}
