set value to ThreadLocal - Java java.lang

Java examples for java.lang:ThreadLocal

Description

set value to ThreadLocal

Demo Code


//package com.java2s;
import java.util.HashMap;
import java.util.Map;

public class Main {
    public static void main(String[] argv) throws Exception {
        String attribute = "java2s.com";
        Object value = "java2s.com";
        set(attribute, value);/*from   w  w w  . j  av a2  s. c  o m*/
    }

    private static final ThreadLocal SESSION_MAP = new ThreadLocal();

    public static void set(String attribute, Object value) {
        Map map = (Map) SESSION_MAP.get();

        if (map == null) {
            map = new HashMap();
            SESSION_MAP.set(map);
        }

        map.put(attribute, value);
    }

    public static Object get(String attribute) {
        Map map = (Map) SESSION_MAP.get();
        return map.get(attribute);
    }

    public static <T> T get(String attribute, Class<T> clazz) {
        return (T) get(attribute);
    }
}

Related Tutorials