Skip to content

Instantly share code, notes, and snippets.

@hkarakose
Created June 22, 2021 21:29
Show Gist options
  • Save hkarakose/2931c5e185cf20f806f314f8f70535f8 to your computer and use it in GitHub Desktop.
Save hkarakose/2931c5e185cf20f806f314f8f70535f8 to your computer and use it in GitHub Desktop.
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.HashMap;
/**
* User: ehaskah
* Date: 26/10/11
* Time: 22:29
*/
public class CurrentThreadContext {
private static final Logger logger = LoggerFactory.getLogger(CurrentThreadContext.class);
private static final ThreadLocal<HashMap<String, Object>> SCOPE_CONTEXT = new ThreadLocal<HashMap<String, Object>>();
private CurrentThreadContext() {
}
/**
* Developer is supposed to call this method at the end of current transaction or at the beginning of a new transaction
*
* It is the developer's responsibility to call this method at the right time.
*/
public static void clear() {
// logger.debug("Clearing thread context");
HashMap map = SCOPE_CONTEXT.get();
if (map != null) {
map.clear();
}
SCOPE_CONTEXT.remove();
}
public static void put(String key, Object value) {
HashMap<String, Object> map = SCOPE_CONTEXT.get();
if (map == null) {
map = new HashMap<>();
SCOPE_CONTEXT.set(map);
}
map.put(key, value);
}
public static Object get(String key) {
HashMap map = SCOPE_CONTEXT.get();
if (map == null) {
return null;
}
return map.get(key);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment