How to correctly handle ThreadLocal.get() returning null

Posted 邱明成

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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();
}

以上是关于How to correctly handle ThreadLocal.get() returning null的主要内容,如果未能解决你的问题,请参考以下文章

How to request a Pull Request in a correct way on GitHub

How to handle your webdriver exceptions

configure-nginx-how-to-handle-500-error-on-upstream-itself-while-nginx-handle

How to handle Appsettings for .net core 3.1 self contained single file publish

How to handle Appsettings for .net core 3.1 self contained single file publish

tensorflow读取jpg格式图片报错 ValueError: Only know how to handle extensions: ['png']; with Pillow i