### Question:
SimpleSpinlock { public V executeWithSpinLock(Callable<V> e) throws Exception { while (true) { while (alreadyLocked()) { } if (!lock()) { continue; } try { return e.call(); } finally { unlock(); } } }  V executeWithSpinLock(Callable<V> e);  }### Answer:
@Test public void testExecuteWithSpinlockReturnLong() throws Exception { final int THREAD_COUNT = 10; final AtomicInteger cnt = new AtomicInteger(); final ExecutorService executor = Executors .newFixedThreadPool(THREAD_COUNT); for (int i = 0; i < THREAD_COUNT; i++) { executor.submit(new Callable<Long>() { public Long call() throws Exception { long res = simpleSpinlock .executeWithSpinLock(new CallableWithLong()); assertThat("Result is not matched", res, is(0L)); cnt.incrementAndGet(); return res; } }); } executor.shutdown(); executor.awaitTermination(THREAD_COUNT, TimeUnit.SECONDS); assertThat("Only " + cnt.get() + " internal threads were executed", cnt.get(), is(THREAD_COUNT)); }
@Test public void testExecuteWithSpinlockThrowsException() throws Exception { final int THREAD_COUNT = 10; final AtomicInteger cnt = new AtomicInteger(); final ExecutorService executor = Executors .newFixedThreadPool(THREAD_COUNT); for (int i = 0; i < THREAD_COUNT; i++) { executor.submit(new Callable<Long>() { public Long call() throws Exception { try { simpleSpinlock .executeWithSpinLock(new CallableWithException()); fail("Exception should be thrown in CallableWithException.call() invocation"); } catch (Exception ex) { } cnt.incrementAndGet(); return 0L; } }); } executor.shutdown(); executor.awaitTermination(THREAD_COUNT, TimeUnit.SECONDS); assertThat("Only " + cnt.get() + " internal threads were executed", cnt.get(), is(THREAD_COUNT)); }