ThreadLocal

介绍:

ThreadLocal : 是thread的一个局部变量 , 它并不能编写一个多线程程序, 这个变量只存在当前线程里面, 对解决多线程程序的并发问题有一一定的启示作用

ThreadLocal 本质就是一个map, 以当前线程对象作为key, 以set设置的数据做为value

/**
 * Sets the current thread's copy of this thread-local variable
 * to the specified value.  Most subclasses will have no need to
 * override this method, relying solely on the {@link #initialValue}
 * method to set the values of thread-locals.
 *
 * @param value the value to be stored in the current thread's copy of
 *        this thread-local.
 */
public void set(T value) {
    Thread t = Thread.currentThread();
    ThreadLocalMap map = getMap(t);
    if (map != null)
        map.set(this, value);
    else
        createMap(t, value);
}

/**
 * Returns the value in the current thread's copy of this
 * thread-local variable.  If the variable has no value for the
 * current thread, it is first initialized to the value returned
 * by an invocation of the {@link #initialValue} method.
 *
 * @return the current thread's value of this thread-local
 */
public T get() {
    Thread t = Thread.currentThread();
    ThreadLocalMap map = getMap(t);
    if (map != null) {
        ThreadLocalMap.Entry e = map.getEntry(this);
        if (e != null) {
            @SuppressWarnings("unchecked")
            T result = (T)e.value;
            return result;
        }
    }
    return setInitialValue();
}
  • 将当前线程局部变量的值删除,目的是为了减少内存的占用,该方法是JDK 1.5 新增的方法。需要指出的是,当线程结束后,对应该线程的局部变量将自动被垃圾回收,所以显式调用该方法清除线程的局部变量并不是必须的操作,但它可以加快内存回收的速度。

在业务中用的tomcat线程池

  • 线程请求结束了, 线程没有结束, 是要把线程还到线程池里面, 线程永远都结束不了, 对应的线程不能自动被垃圾回收,
  • 因为线程并没有结束, 如果不去手动的删除,就会导致【内存泄漏】
  • 【内存泄漏】: 解决方案 : 手动remove,
  • 在视图渲染完成之后就可以 remove了

你可能感兴趣的:(Java,java,多线程,内存泄漏)