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

public class Correct {
    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 extends Thread {
        private Data d;
        public Processor(Data d) {
            this.d = d;
        }
        @Override
        public void run() {
            // simulate some work between get and set
            synchronized(d) {
                String s = d.getS();
                Thread.yield();
                d.setS(s + 'X');
            }
        }
    }
    public static void test(int njobs, int nthreads) {
        // setup data
        Data d = new Data("");
        // process with shared data
        for(int i = 0; i < njobs / nthreads; i++) {
            // create threads
            Thread[] t = new Thread[nthreads];
            for(int j = 0; j < nthreads; j++) {
                t[j] = new Processor(d);
            }
            // start threads
            for(int j = 0; j < nthreads; j++) {
                t[j].start();
            }
            // wait for threads to complete
            for(int j = 0; j < nthreads; j++) {
                try {
                    t[j].join();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
        System.out.printf("%d threads : expected = %d, actual = %d\n", nthreads, njobs, d.getS().length());
    }
    public static void main(String[] args) {
        test(2560, 1);
        test(2560, 2);
        test(2560, 4);
        test(2560, 8);
        test(2560, 16);
        test(2560, 32);
        test(2560, 64);
    }
}
