// 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.Arrays;

public class Adv {
    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 {
        private Data d;
        public Processor(Data d) {
            this.d = d;
        }
        public void run() {
            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();
            }
        }
    }
    public static void test(boolean par, int njobs) {
        // setup data
        Data[] d = new Data[njobs];
        for(int i = 0; i < njobs; i++) {
            d[i] = new Data("X");
        }
        // process
        long t1 = System.currentTimeMillis();
        if(par) {
            Arrays.stream(d).parallel().forEach(o -> (new Processor(o)).run());
        } else {
            Arrays.stream(d).sequential().forEach(o -> (new Processor(o)).run());
        }
        long t2 = System.currentTimeMillis();
        System.out.printf("%d jobs executing in %s threads : %.1f seconds\n", njobs, par ? "many" : "one", (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(false, 256);
        test(true, 256);
    }
}
