Logback MDC with ThreadPools or Spring Async
<p>I'm trying to determine how thread-safe <code>MDC</code> is when using Cacheable ThreadPools or Spring's Async annotation.</p>

<p>I have a method that calls several <code>CompletableFuture&lt;&gt;</code> and executes them using thread pools</p>

<pre><code>@Async
public CompletableFuture&lt;List&gt; someMethod(String request) {
    try {
        MDC.put("request", request)
        MDC.put("loggable1", "loggable1");
        MDC.put("loggable2", "loggable2");
        log.info("Log Event");
    } finally {
        MDC.clear();
    }
}
</code></pre>

<p>Relevant parts from Logback's MDCAdapter</p>

<pre><code>final ThreadLocal&lt;Map&lt;String, String&gt;&gt; copyOnThreadLocal = new ThreadLocal&lt;Map&lt;String, String&gt;&gt;();

public void put(String key, String val) throws IllegalArgumentException {
    if (key == null) {
        throw new IllegalArgumentException("key cannot be null");
    }

    Map&lt;String, String&gt; oldMap = copyOnThreadLocal.get();
    Integer lastOp = getAndSetLastOperation(WRITE_OPERATION);

    if (wasLastOpReadOrNull(lastOp) || oldMap == null) {
        Map&lt;String, String&gt; newMap = duplicateAndInsertNewMap(oldMap);
        newMap.put(key, val);
    } else {
        oldMap.put(key, val);
    }
}

public void clear() {
    lastOperation.set(WRITE_OPERATION);
    copyOnThreadLocal.remove();
}


public void remove(String key) {
    if (key == null) {
        return;
    }
    Map&lt;String, String&gt; oldMap = copyOnThreadLocal.get();
    if (oldMap == null)
        return;

    Integer lastOp = getAndSetLastOperation(WRITE_OPERATION);

    if (wasLastOpReadOrNull(lastOp)) {
        Map&lt;String, String&gt; newMap = duplicateAndInsertNewMap(oldMap);
        newMap.remove(key);
    } else {
        oldMap.remove(key);
    }
}
</code></pre>

<p>Since ThreadPools reuse already spawned threads and MDC uses a ThreadLocal context map. Is it possible that we can either lose or corrupt values stored in MDC? If so what are potential scenarios that this can happen?</p>