nutzam / nutz

Nutz -- Web Framework(Mvc/Ioc/Aop/Dao/Json) for ALL Java developer
https://nutzam.com
Apache License 2.0
2.53k stars 942 forks source link

Mvcs.resetALL() 和 NutMvcContext.reqThreadLocal 这里有内存泄漏 #634

Closed LongEth closed 9 years ago

LongEth commented 10 years ago

Mvcs.resetALL() 和 NutMvcContext.reqThreadLocal 这里有内存泄漏,而且逻辑好像也不对

public ThreadLocal<Context> reqThreadLocal = new ThreadLocal<Context>() {
        protected Context initialValue() {
            return Lang.context();
        }
    };

这里每次Web请求调用,肯定会初始化reqThreadLocal一次,而在线程结束的时候,没有给reqThreadLocal设置null,导致ThreadLocal线程内存会出现问题。 再看下面程序(Mvcs.java):

    /**
     * 重置当前线程所持有的对象
     */
    public static Context resetALL() {
        Context context = ctx.reqThreadLocal.get();
        NAME.set(null);
//这里给ThreadLocal赋了个空的SimpleContext,new 的对象肯定不为空
        ctx.reqThreadLocal.set(Lang.context());
        return context;
    }

然后每次线程ThreadLocal都会出现未设置NULL 典型的样子是每次Tomcat重启,都会报一堆下面的错误:

严重: The web application  created a ThreadLocal with key of type [java.lang.ThreadLocal] (value [java.lang.ThreadLocal@4a05e593]) and a value of type [org.nutz.lang.util.SimpleContext] (value [{}]) but failed to remove it when the web application was stopped. Threads are going to be renewed over time to try and avoid a probable memory leak.
2014-4-28 10:29:30 org.apache.catalina.loader.WebappClassLoader checkThreadLocalMapForLeaks
wendal commented 10 years ago

未解决.

LongEth commented 10 years ago

问题出现在resetALL的 ctx.reqThreadLocal.set(Lang.context()); 我觉得一个解决办法是这里改成: ctx.reqThreadLocal.set(null); 然后在setTLs中加入ctx.reqThreadLocal.set(Lang.context());进行初始化