### Question:
ListenerWrapper implements Consumer<CalculationResults> { @Override public void accept(CalculationResults result) { CalculationResults nextResult; lock.lock(); try { if (executing) { queue.add(result); return; } else { executing = true; nextResult = result; } } finally { lock.unlock(); } for (;;) { listenerLock.lock(); try { for (CalculationResult cell : nextResult.getCells()) { listener.resultReceived(nextResult.getTarget(), cell); } } catch (RuntimeException e) { log.warn("Exception invoking listener.resultReceived", e); } finally { listenerLock.unlock(); } lock.lock(); try { if (++tasksReceived == tasksExpected) { listenerLock.lock(); try { listener.calculationsComplete(); } catch (RuntimeException e) { log.warn("Exception invoking listener.calculationsComplete", e); } finally { listenerLock.unlock(); } return; } else if (queue.isEmpty()) { executing = false; return; } else { nextResult = queue.remove(); } } finally { lock.unlock(); } } } ListenerWrapper(CalculationListener listener, int tasksExpected, List<CalculationTarget> targets, List<Column> columns); @Override void accept(CalculationResults result);  }### Answer:
@Test public void concurrentExecution() throws InterruptedException { int nThreads = Runtime.getRuntime().availableProcessors(); int resultsPerThread = 10; ConcurrentLinkedQueue<String> errors = new ConcurrentLinkedQueue<>(); CountDownLatch latch = new CountDownLatch(1); int expectedResultCount = nThreads * resultsPerThread; Listener listener = new Listener(errors, latch); Consumer<CalculationResults> wrapper = new ListenerWrapper(listener, expectedResultCount, ImmutableList.of(), ImmutableList.of()); ExecutorService executor = Executors.newFixedThreadPool(nThreads); CalculationResult result = CalculationResult.of(0, 0, Result.failure(FailureReason.ERROR, "foo")); CalculationTarget target = new CalculationTarget() {}; CalculationResults results = CalculationResults.of(target, ImmutableList.of(result)); IntStream.range(0, expectedResultCount).forEach(i -> executor.submit(() -> wrapper.accept(results))); latch.await(); executor.shutdown(); if (!errors.isEmpty()) { String allErrors = errors.stream().collect(joining("\n")); fail(allErrors); } }