001package io.ebean.config;
002
003import org.slf4j.MDC;
004
005import java.util.Map;
006import java.util.concurrent.Callable;
007
008/**
009 * Propagates MDC context for tasks executed in the background.
010 */
011public final class MdcBackgroundExecutorWrapper implements BackgroundExecutorWrapper {
012
013  /**
014   * Wrap the task with MDC context if defined.
015   */
016  @Override
017  public <T> Callable<T> wrap(Callable<T> task) {
018    final Map<String, String> map = MDC.getCopyOfContextMap();
019    if (map == null) {
020      return task;
021    } else {
022      return () -> {
023        MDC.setContextMap(map);
024        try {
025          return task.call();
026        } finally {
027          MDC.clear();
028        }
029      };
030    }
031  }
032
033  /**
034   * Wrap the task with MDC context if defined.
035   */
036  @Override
037  public Runnable wrap(Runnable task) {
038    final Map<String, String> map = MDC.getCopyOfContextMap();
039    if (map == null) {
040      return task;
041    } else {
042      return () -> {
043        MDC.setContextMap(map);
044        try {
045          task.run();
046        } finally {
047          MDC.clear();
048        }
049      };
050    }
051  }
052}