线程本地间歇性地返回null

时间:2015-08-13 03:32:57

标签: java multithreading thread-local

我正在使用ThreadLocal来存储上下文变量。我的组件是SOA - rest组件。问题是threadLocal是间歇性地返回null。我确信在使用之前我会填充它。我正在从JAX-RS repsonse过滤器清除它。

static final修饰符可以导致此问题吗?只要将其指定为InheritableThreadLocal,所有子线程都可以使用threadLocal吗?

import java.util.Map;

/**
 * Contains the context object and 
 */
public class ContextHolder {

    private static final ThreadLocal<Map<String, Object>> threadLocal = new InheritableThreadLocal<Map<String, Object>>();

    /**
     * Private constructor so that nobody can create an instance.
     */
    private ContextHolder() {
    }

    /**
     * Initializes the threadlocal with the passed map.
     * 
     * @param context - 
     */
    public static void initConext(Map<String, Object> context) {
        threadLocal.set(context);
    }

    /**
     * Returns the context from this thread.
     * 
     * @return Context
     */
    public static Map<String, Object> getContext() {
        return threadLocal.get();
    }

    /**
     * Clears the context from the threadlocal.
     */
    public static void clearConext() {
        threadLocal.remove();
    }

}

1 个答案:

答案 0 :(得分:2)

static final修饰符不应导致此问题。所有ThreadLocal个对象都可供所有子线程使用;它只是每个线程不同的内容。 InheritableThreadLocal的不同之处在于子线程&#39;初始值是继承的,而不是最初设置为null。请注意,只继承初始值,而不是父线程中的后续修改。

在尝试将值从父线程传递到子线程时,很可能存在代码同步的错误。处理多个线程时,&#34;之前&#34;具有非常复杂且有时违反直觉的含义,尤其是在早期版本的Java中。

相关问题