ServiceContextAwareExecutorService implements ExecutorService { @Override public <T> Future<T> submit(Callable<T> task) { return _delegateExecutor.submit(new ServiceContextAwareCallable<>(task)); } ServiceContextAwareExecutorService(ExecutorService delegate); @Override void shutdown(); @Override List<Runnable> shutdownNow(); @Override boolean isShutdown(); @Override boolean isTerminated(); @Override boolean awaitTermination(long timeout, TimeUnit unit); @Override Future<T> submit(Callable<T> task); @Override Future<T> submit(Runnable task, T result); @Override Future<?> submit(Runnable task); @Override List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks); @Override List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks, long timeout, TimeUnit unit); @Override T invokeAny(Collection<? extends Callable<T>> tasks); @Override T invokeAny(Collection<? extends Callable<T>> tasks, long timeout, TimeUnit unit); @Override void execute(Runnable command);  }
@Test public void submitCallable() throws ExecutionException, InterruptedException { assertFalse(_underlying.submit(callable()).get()); assertTrue(_executor.submit(callable()).get()); }
@Test public void submitRunnable() throws InterruptedException { final ArrayBlockingQueue<Boolean> queue = new ArrayBlockingQueue<>(1); Runnable r = new Runnable() { @Override public void run() { boolean b = ThreadLocalServiceContext.getInstance() != null; try { queue.put(b); } catch (InterruptedException e) { throw new RuntimeException(e); } } }; _underlying.submit(r); assertFalse(queue.take()); _executor.submit(r); assertTrue(queue.take()); _underlying.submit(r, null); assertFalse(queue.take()); _executor.submit(r, null); assertTrue(queue.take()); }
@Test public void amendContext() throws InterruptedException, ExecutionException { ThreadLocalServiceContext.init(ServiceContext.of(String.class, "StringService")); ExecutorService executor = new ServiceContextAwareExecutorService(_underlying); assertThat(executor.submit(stringCallable()).get(), is("WithString")); ThreadLocalServiceContext.init(ServiceContext.of(Integer.class, 42)); assertThat(executor.submit(stringCallable()).get(), is("WithoutString")); }