Remove/Clear the value of the passed in key in ThreadLocal - Java java.lang

Java examples for java.lang:ThreadLocal

Description

Remove/Clear the value of the passed in key in ThreadLocal

Demo Code


import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpSession;

public class Main{
    public static void main(String[] argv) throws Exception{
        String key = "java2s.com";
        remove(key);/*from  w  w  w  .  java  2  s  . c  om*/
    }
    private static ThreadLocal<Map<String, Object>> threadLocal = new ThreadLocal<Map<String, Object>>();
    /**
     * Remove/Clear the value of the passed in key
     * @param key
     */
    public static void remove(String key) {
        if (((Map<String, Object>) threadLocal.get()).containsKey(key)) {
            ((Map<String, Object>) threadLocal.get()).remove(key);
        }
    }
    /**
     * Get the value of the key set from the {@link ThreadLocal} instance
     * @param key
     * @return
     */
    public static Object get(String key) {
        if (threadLocal.get() == null) {
            return null;
        }

        return ((Map<String, Object>) threadLocal.get()).get(key);
    }
}

Related Tutorials