// 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) 
public class ThreadSafeTest {
	private int n;
	public int getN() {
		return n;
	}
	public void setN(int n) {
		this.n = n;
	}
	public void test(TraditionalOrLambda o) throws InterruptedException {
		n = 0;
		Thread[] t = new Thread[8];
		for(int i = 0; i < t.length; i++) {
			t[i] = new ThreadSafeTestThread(o, this, 1000000);
		}
		for(int i = 0; i < t.length; i++) {
			t[i].start();
		}
		for(int i = 0; i < t.length; i++) {
			t[i].join();
		}
		System.out.println(n);
	}
	public static void main(String[] args) throws InterruptedException {
		ThreadSafeTest tst = new ThreadSafeTest();
		tst.test(new TraditionalUnsafe());
		tst.test(new TraditionalSafe());
		tst.test((subj) -> subj.setN(subj.getN() + 1));
		tst.test((subj) -> { synchronized(subj) { subj.setN(subj.getN() + 1); } });
	}
}

class ThreadSafeTestThread extends Thread {
	private TraditionalOrLambda o;
	private ThreadSafeTest subj;
	private int nit;
	public ThreadSafeTestThread(TraditionalOrLambda o, ThreadSafeTest subj, int nit) {
		this.o = o;
		this.subj = subj;
		this.nit = nit;
	}
	public void run() {
		for(int i = 0; i < nit; i++) {
			o.incr(subj);
		}
	}
}

@FunctionalInterface
interface TraditionalOrLambda {
	public void incr(ThreadSafeTest subj);
}

class TraditionalSafe implements TraditionalOrLambda {
	public void incr(ThreadSafeTest subj) {
		synchronized(subj) {
			subj.setN(subj.getN() + 1);
		}
	}
}

class TraditionalUnsafe implements TraditionalOrLambda {
	public void incr(ThreadSafeTest subj) {
		subj.setN(subj.getN() + 1);
	}
}
