package wat; public class ThreadContention { public static void main(String[] args) throws InterruptedException { // dummy thread to get the HotSpot VM to compile OpThread.op() Thread opThread = new OpThread(1048576L); opThread.start(); opThread.join(); // real benchmarks benchmark(2, 80000000L); benchmark(64, 2500000L); } private static void benchmark(final int numThreads, final long iterationsEach) throws InterruptedException { Thread[] threads = new Thread[numThreads]; for (int i = 0; i < threads.length; i++) threads[i] = new OpThread(iterationsEach); long startTime = System.currentTimeMillis(); for (int i = 0; i < threads.length; i++) threads[i].start(); for (int i = 0; i < threads.length; i++) threads[i].join(); long duration = System.currentTimeMillis() - startTime; System.out.println(numThreads + " ran in " + duration + " millsec"); } static class OpThread extends Thread { private final long iterations; private final int[] temp = { 0xCAFEBABE, 0xCAFEBABE, 0xCAFEBABE, 0xCAFEBABE }; // ;) private volatile int cur = 0; public OpThread(long iterations) { this.iterations = iterations; } @Override public void run() { for (long iteration = 0; iteration < iterations; iteration++) { temp[(cur + 1) % temp.length] = op(temp[cur]); cur = (cur + 1) % temp.length; } } private int op(final int value) { // some random operation that doesn't involve I/O or // garbage collection, but does involve memory access return Integer.rotateLeft(value ^ 0x1337BEEF * 7 + (int) ((float) value / 1.337357f / Math.random()), 16) | 0xAA005500; } } }