// Collection of code snippets by Arne Vajhøj 
// (from articles on eksperten.dk / vajhoej.dk written sometime between 2004 and now) 
package threads;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

public class Pool {
    public static class Data {
        private String s;
        public Data(String s) {
            this.s = s;
        }
        public String getS() {
            return s;
        }
        public void setS(String s) {
            this.s = s;
        }
    }
    public static class Processor implements Callable<Void> {
        private Data d;
        public Processor(Data d) {
            this.d = d;
        }
        @Override
        public Void call() {
            try {
                // simulate a lot of work that takes 0.1 second
                String s = d.getS();
                Thread.sleep(100);
                d.setS(s + 'X');
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return null;
        }
    }
    public static void test(int njobs, int nthreads) {
        // setup data
        Data[] d = new Data[njobs];
        for(int i = 0; i < njobs; i++) {
            d[i] = new Data("X");
        }
        long t1 = System.currentTimeMillis();
        ExecutorService es = Executors.newFixedThreadPool(nthreads);
        // submit jobs
        @SuppressWarnings("unchecked")
        Future<Void>[] res = new Future[njobs];
        for(int i = 0; i < njobs; i++) {
            res[i] = es.submit(new Processor(d[i]));
        }
        // wait for jobs to complete
        for(int i = 0; i < njobs; i++) {
            try {
                res[i].get();
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (ExecutionException e) {
                e.printStackTrace();
            }
        }
        es.shutdown();
        long t2 = System.currentTimeMillis();
        System.out.printf("%d jobs executing in %d threads : %.1f seconds\n", njobs, nthreads, (t2 - t1) / 1000.0);
        // check data
        for(int i = 0; i < njobs; i++) {
            if(!d[i].getS().equals("XX")) System.out.println("Ooops");
        }
    }
    public static void main(String[] args) {
        test(256, 1);
        test(256, 2);
        test(256, 4);
        test(256, 8);
        test(256, 16);
        test(256, 32);
        test(256, 64);
    }
}
