How to correctly handle ThreadLocal.get() returning null

Java's ThreadLocals make certain things easy, but special care must be taken to make sure they are removed from threads when they are no longer needed. If ThreadLocals are not removed from threads, they can easily cause memory leaks, because threads can live much longer than the applications that are executed on a thread.

Consider a web application running inside a servlet container like Tomcat. Each request is handled by a thread from a thread pool. These threads can live well after you web app is undeployed from the server.

One of the easiest ways to get this wrong is to assume that ThreadLocal.get() returning null means that the ThreadLocal is not installed in the thread. This is not the case.

Each thread has a map of ThreadLocals, and when ThreadLocal.get() is called for the first time, it actually installs the ThreadLocalinto that ThreadLocal map for the current thread with the default value, which is usually null. You must still remove the ThreadLocal from the thread by calling ThreadLocal.remove().

As a rule of thumb, for ThreadLocals where the default value is null, if get() returns nullremove() should be called immediately.

I have written a class that does most of this for me:

/**
 * A conservative {@link ThreadLocal} that removes itself from the thread
 * whenever its value is {@code null}.
 * @author Jesse Long
 * @param <T> The type of the value stored in this {@link ThreadLocal}
 */
public abstract class ConservativeThreadLocal<T>
        extends ThreadLocal<T>
{
    /**
     * Returns the current value of the variable, or {@code null} if it has not
     * been set. This method takes care to remove this {@link ThreadLocal} from
     * the thread if the value has not been set.
     * @return the current value of the variable, or {@code null} if it has not
     * been set.
     */
    @Override
    public final T get()
    {
        T t = super.get();
        if (t == null){
            remove();
        }
        return t;
    }

    /**
     * Returns {@code null}. This implementation always returns {@code null} so
     * that this {@link ThreadLocal} implementation can use its absent on a
     * thread as an indication that the value is not set.
     * @return {@code null}
     */
    @Override
    protected final T initialValue()
    {
        return null;
    }

    /**
     * Returns the current value of the variable. If the value has not been
     * set, and {@code create} is {@code true}, then the {@link #create()}
     * method is called, the value of the {@link ThreadLocal} is set to the
     * return value of {@link #create()}, and is returned from this method. If
     * the value has not been set, and {@code create} is {@code false}, then
     * this method behaves exactly the same as the {@link #get()} method.
     * 
     * @return the current value of the variable, or the default value if
     * {@code create} is {@code true}.
     * 
     * @param create whether or not to set the default value if it has not yet
     * been set.
     */
    public T get(boolean create)
    {
        T t = get();
        if (t == null && create){
            t = create();
            set(t);
        }
        return t;
    }

    /**
     * Sets the current value. If {@code value} is {@code null}, then this
     * {@link ThreadLocal} is removed from the thread.
     * @param value The value to set.
     */
    @Override
    public void set(T value)
    {
        if (value == null){
            remove();
        }else{
            super.set(value);
        }
    }

    /**
     * Returns the default value for this object.
     * @return the default value for this object.
     * @see #get(boolean) 
     */
    protected abstract T create();
}

转载于:https://www.cnblogs.com/qiumingcheng/p/8448455.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值