I'm working on an app where we have a decorator Log4JRunnable class that
used to wrap runnables submitted to a thread pool. It retrieves a copy of
the MDC from the submitting thread (code included below). The problem that I
am running into is that occasionally a ConcurrentModificationException is
being thrown when I iterate over the entries in the hashtable. I've looked
of the Log4J and JDK code an couldn't find anything that stuck out. I know
that this might now be a Log4J specific problem, but maybe there's something
I missed. Any insight into this would be appreciated.
Thanks in advance.
Matt
public class Log4JRunnable implements Runnable {
private final Runnable runnable;
private final Hashtable mdc;
public Log4JRunnable(Runnable runnable) {
runnable = runnable;
mdc = (MDC.getContext() != null) ? (Hashtable) MDC.getContext
().clone() : null;
}
public void run() {
if (mdc != null) {
for (Iterator i = mdc.entrySet().iterator(); i.hasNext(); ) {
// getting ConcurrentModificationException here
Map.Entry entry = (Map.Entry) i.next();
MDC.put((String) entry.getKey(), entry.getValue());
}
}
runnable.run();
if (mdc != null) {
for (Iterator i = mdc.entrySet().iterator(); i.hasNext(); ) {
Map.Entry entry = (Map.Entry) i.next();
MDC.remove((String) entry.getKey());
}
}
}
}