MDCUtil { public static Executor withMDC() { return runnable -> ForkJoinPool.commonPool().execute(withMDC(runnable)); } private  MDCUtil(); static Executor withMDC(); static Executor withMDC(Executor executor); static Runnable withMDC(Runnable r); static Callable<V> withMDC(Callable<V> r); static MDC.MDCCloseable safePutCloseable(String key, String value);  }
@Test @Repeat(times = 10000, threads = 4) public void withMDCRunnable() throws ExecutionException, InterruptedException { MDC.put("foo", "bar"); final CompletableFuture<String> value = new CompletableFuture<>(); EXECUTOR_SERVICE.submit(withMDC(() -> value.complete(MDC.get("foo")))).get(); assertThat(value.get(), is("bar")); }
@Test @Repeat(times = 10000, threads = 4) public void withMDCCallable() throws ExecutionException, InterruptedException { MDC.put("foo", "bar"); final String value = EXECUTOR_SERVICE.submit(withMDC(() -> MDC.get("foo"))).get(); assertThat(value, is("bar")); }
@Test @Repeat(times = 10000, threads = 4) public void withMDCCommonPool() throws ExecutionException, InterruptedException { MDC.put("foo", "bar"); final CompletableFuture<String> value1 = new CompletableFuture<>(); final CompletableFuture<String> value2 = new CompletableFuture<>(); CompletableFuture.runAsync( () -> value1.complete(MDC.get("foo")), withMDC()) .thenRun(() -> value2.complete(MDC.get("foo"))) .get(); assertThat(value1.getNow(""), is("bar")); assertThat(value2.getNow(""), is("bar")); final Map<String, String> mdc = CompletableFuture .supplyAsync(MDC::getCopyOfContextMap) .get(); assertThat(mdc, is(anyOf(nullValue(), is(emptyMap())))); }
@Test @Repeat(times = 10000, threads = 4) public void withMDCExecutor() throws ExecutionException, InterruptedException { MDC.put("foo", "bar"); final CompletableFuture<String> value1 = new CompletableFuture<>(); final CompletableFuture<String> value2 = new CompletableFuture<>(); CompletableFuture.runAsync( () -> value1.complete(MDC.get("foo")), withMDC(EXECUTOR_SERVICE)) .thenRun(() -> value2.complete(MDC.get("foo"))) .get(); assertThat(value1.getNow(""), is("bar")); assertThat(value2.getNow(""), is("bar")); final Map<String, String> mdc = EXECUTOR_SERVICE .submit(MDC::getCopyOfContextMap) .get(); assertThat(mdc, is(anyOf(nullValue(), is(emptyMap())))); }