All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.undefinedlabs.scope.context.ContextStrategyImpl Maven / Gradle / Ivy

package com.undefinedlabs.scope.context;

import com.undefinedlabs.scope.bootstrap.ContextStrategy;
import com.undefinedlabs.scope.logger.ScopeLogger;
import com.undefinedlabs.scope.logger.ScopeLoggerResolver;
import java.util.Map;
import java.util.WeakHashMap;
import java.util.concurrent.Callable;

public class ContextStrategyImpl implements ContextStrategy {

  private static final ScopeLogger LOGGER = ScopeLoggerResolver.INSTANCE.get();
  private final Map savedContexts = new WeakHashMap<>();

  @Override
  public Runnable wrapInCurrentContext(Runnable runnable) {
    return ImmutableContext.current().wrap(runnable);
  }

  @Override
  public Callable wrapInCurrentContext(Callable callable) {
    return ImmutableContext.current().wrap(callable);
  }

  @Override
  public void saveContextForThread(Thread thread) {
    savedContexts.put(
        thread, new ContextContainer(Thread.currentThread(), ImmutableContext.current()));
  }

  @Override
  public void attachContextForThread(Thread thread) {
    if (Thread.currentThread() == thread) {
      final ContextContainer contextContainer = savedContexts.get(thread);
      if (contextContainer != null) {
        savedContexts.remove(thread);
        final ImmutableContext context = contextContainer.getContext();
        final SharedContextMap sharedContextMap =
            SharedContextMap.SHARED_CONTEXT_MAP_KEY.get(context);

        context.attach();
        LOGGER.trace(
            "--- Propagated context with map "
                + sharedContextMap
                + " from "
                + contextContainer.getOrigThread()
                + " to "
                + thread);
      }
    }
  }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy