publicclassBenchController{ private Random random = new Random(); privatestatic Object[] lockObj; privatestatic AtomicReference<Integer>[] locks; static { lockObj = new Object[100]; for (int i = 0; i < lockObj.length; i++) { lockObj[i] = new Object(); }
locks = new AtomicReference[100]; for (int i = 0; i < locks.length; i++) { locks[i] = new AtomicReference<Integer>(null); } }
@RequestMapping("a/{id}") @ResponseBody publiclonga(@PathVariable("id")int id) throws Exception { long start = System.currentTimeMillis(); int index = id % 100; long inner = 0; synchronized (lockObj[index]) { inner = test(); } long result = System.currentTimeMillis() - start; System.out.println("all: " + result + " inner: " + inner); return result; }
@RequestMapping("b/{id}") @ResponseBody publiclongb(@PathVariable("id")int id) throws Exception { long start = System.currentTimeMillis(); id = id % 100; AtomicReference<Integer> lock = locks[id]; int b = 0; while (!lock.compareAndSet(null, id)) { b = 1 + 1; } long inner = test(); boolean flag = lock.compareAndSet(id, null); long result = System.currentTimeMillis() - start; System.out.println("all: " + result + " inner: " + inner + " flag:" + flag); System.out.println(b); return result; }
@OutputTimeUnit(TimeUnit.NANOSECONDS) @Warmup(iterations = 5) @Measurement(iterations = 10, time = 5, timeUnit = TimeUnit.SECONDS) @BenchmarkMode(Mode.AverageTime) @State(Scope.Benchmark) public class Test { private AtomicInteger atomic; private Object lock = new Object(); private int i = 0; @Setup public void setUp() { atomic = new AtomicInteger(0); }
@Fork(1) @Threads(10) @Benchmark public int incrementAtomic() { return atomic.incrementAndGet(); }
@Fork(1) @Threads(10) @Benchmark public int cas() { int i; do { i = atomic.get(); } while (!atomic.compareAndSet(i, i + 1)); return i + 1; }
@Fork(1) @Threads(10) @Benchmark public int incrementSync() { synchronized (lock) { ++i; } return i; } }