복붙노트

[SPRING] 이것은 Tomcat에서 메모리 누출을 일으킬 가능성이 매우 높습니까?

SPRING

이것은 Tomcat에서 메모리 누출을 일으킬 가능성이 매우 높습니까?

다른 외부 오픈 소스와 작동하도록 tomcat을 구성했습니다.

그러나, 바람둥이가 몇 분 동안 달리고 난 후에 나는 다음을 얻는다 :

무엇이 그것을 일으킬 수 있습니까?

어디를 봐야하나요? Tomcat에서 데이터 풀링이 가능합니까?

Tomcat의 Threads는 무엇을 의미합니까?

편집 됨

여기 내 모든 흔적이있다. 응용 프로그램은 여전히 ​​실행 중일 때 컨텍스트를 다시로드하는 것처럼 보입니다. 이유는 모르겠습니다!

Mar 13, 2011 10:56:12 PM org.apache.catalina.core.StandardContext reload
INFO: Reloading this Context has started
Mar 13, 2011 10:56:12 PM org.apache.catalina.core.StandardWrapper unload
INFO: Waiting for 1 instance(s) to be deallocated
Mar 13, 2011 10:56:13 PM org.apache.catalina.core.StandardWrapper unload
INFO: Waiting for 1 instance(s) to be deallocated
Mar 13, 2011 10:56:14 PM org.apache.catalina.core.StandardWrapper unload
INFO: Waiting for 1 instance(s) to be deallocated
Mar 13, 2011 10:56:14 PM org.apache.catalina.core.ApplicationContext log
INFO: Closing Spring root WebApplicationContext
Mar 13, 2011 10:56:15 PM org.apache.catalina.loader.WebappClassLoader clearReferencesJdbc
SEVERE: The web application [/MyProject] registered the JBDC driver [com.mysql.jdbc.Driver] but failed to unregister it when the web application was stopped. To prevent a memory leak, the JDBC Driver has been forcibly unregistered.
Mar 13, 2011 10:56:15 PM org.apache.catalina.loader.WebappClassLoader clearReferencesJdbc
SEVERE: The web application [/MyProject] registered the JBDC driver [oracle.jdbc.driver.OracleDriver] but failed to unregister it when the web application was stopped. To prevent a memory leak, the JDBC Driver has been forcibly unregistered.
Mar 13, 2011 10:56:15 PM org.apache.catalina.loader.WebappClassLoader clearReferencesThreads
SEVERE: The web application [/MyProject] appears to have started a thread named [NioSocketAcceptor-1] but has failed to stop it. This is very likely to create a memory leak.
Mar 13, 2011 10:56:15 PM org.apache.catalina.loader.WebappClassLoader clearReferencesThreads
SEVERE: The web application [/MyProject] appears to have started a thread named [NioProcessor-1] but has failed to stop it. This is very likely to create a memory leak.
Mar 13, 2011 10:56:15 PM org.apache.catalina.loader.WebappClassLoader clearReferencesThreads
SEVERE: The web application [/MyProject] appears to have started a thread named [NioProcessor-4] but has failed to stop it. This is very likely to create a memory leak.
Mar 13, 2011 10:56:15 PM org.apache.catalina.loader.WebappClassLoader clearReferencesThreads
SEVERE: The web application [/MyProject] appears to have started a thread named [bitronix-disk-force-batcher] but has failed to stop it. This is very likely to create a memory leak.
Mar 13, 2011 10:56:15 PM org.apache.catalina.loader.WebappClassLoader clearReferencesThreads
SEVERE: The web application [/MyProject] appears to have started a thread named [bitronix-scheduler] but has failed to stop it. This is very likely to create a memory leak.
Mar 13, 2011 10:56:15 PM org.apache.catalina.loader.WebappClassLoader clearReferencesThreads
SEVERE: The web application [/MyProject] is still processing a request that has yet to finish. This is very likely to create a memory leak. You can control the time allowed for requests to finish by using the unloadDelay attribute of the standard Context implementation.
Mar 13, 2011 10:56:15 PM org.apache.catalina.loader.WebappClassLoader clearReferencesThreads
SEVERE: The web application [/MyProject] appears to have started a thread named [NioProcessor-7] but has failed to stop it. This is very likely to create a memory leak.
Mar 13, 2011 10:56:15 PM org.apache.catalina.loader.WebappClassLoader clearReferencesThreads
SEVERE: The web application [/MyProject] appears to have started a thread named [NioProcessor-2] but has failed to stop it. This is very likely to create a memory leak.
Mar 13, 2011 10:56:15 PM org.apache.catalina.loader.WebappClassLoader clearThreadLocalMap
SEVERE: The web application [/MyProject] created a ThreadLocal with key of type [java.lang.ThreadLocal] (value [java.lang.ThreadLocal@1b5a8e1]) and a value of type [org.mvel2.debug.DebuggerContext] (value [org.mvel2.debug.DebuggerContext@16259fd]) but failed to remove it when the web application was stopped. This is very likely to create a memory leak.
Mar 13, 2011 10:56:15 PM org.apache.catalina.loader.WebappClassLoader clearThreadLocalMap
SEVERE: The web application [/MyProject] created a ThreadLocal with key of type [org.apache.axis.utils.XMLUtils.ThreadLocalDocumentBuilder] (value [org.apache.axis.utils.XMLUtils$ThreadLocalDocumentBuilder@84b0b4]) and a value of type [com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderImpl] (value [com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderImpl@16d2cfa]) but failed to remove it when the web application was stopped. This is very likely to create a memory leak.
Mar 13, 2011 10:56:15 PM org.apache.catalina.loader.WebappClassLoader clearThreadLocalMap
SEVERE: The web application [/MyProject] created a ThreadLocal with key of type [null] (value [com.sun.faces.util.Util$1@16bbac9]) and a value of type [java.util.HashMap] (value [{com.sun.faces.patternCache={ = }}]) but failed to remove it when the web application was stopped. This is very likely to create a memory leak.
Mar 13, 2011 10:56:15 PM org.apache.catalina.loader.WebappClassLoader clearThreadLocalMap
SEVERE: The web application [/MyProject] created a ThreadLocal with key of type [java.lang.ThreadLocal] (value [java.lang.ThreadLocal@1b3f02f]) and a value of type [org.apache.axis.MessageContext] (value [org.apache.axis.MessageContext@5dbd4e]) but failed to remove it when the web application was stopped. This is very likely to create a memory leak.
Mar 13, 2011 10:56:15 PM org.apache.catalina.loader.WebappClassLoader clearThreadLocalMap
SEVERE: The web application [/MyProject] created a ThreadLocal with key of type [org.apache.axis.utils.XMLUtils.ThreadLocalDocumentBuilder] (value [org.apache.axis.utils.XMLUtils$ThreadLocalDocumentBuilder@84b0b4]) and a value of type [com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderImpl] (value [com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderImpl@378584]) but failed to remove it when the web application was stopped. This is very likely to create a memory leak.
Mar 13, 2011 10:56:15 PM org.apache.catalina.loader.WebappClassLoader clearThreadLocalMap
SEVERE: The web application [/MyProject] created a ThreadLocal with key of type [org.springframework.core.NamedThreadLocal] (value [Transactional resources]) and a value of type [java.util.HashMap] (value [{org.hibernate.impl.SessionFactoryImpl@ccc27b=org.springframework.orm.hibernate3.SessionHolder@4f6ada}]) but failed to remove it when the web application was stopped. This is very likely to create a memory leak.
Mar 13, 2011 10:56:15 PM org.apache.catalina.loader.WebappClassLoader clearThreadLocalMap
SEVERE: The web application [/MyProject] created a ThreadLocal with key of type [null] (value [com.sun.faces.application.ApplicationAssociate$1@1f01fcf]) and a value of type [com.sun.faces.application.ApplicationAssociate] (value [com.sun.faces.application.ApplicationAssociate@1b85528]) but failed to remove it when the web application was stopped. This is very likely to create a memory leak.
2011-03-13 22:57:27,734 ERROR (            ContextLoader.java:220)     - Context initialization failed
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'transactionManager' defined in class path resource [applicationContext-hibernate.xml]: Cannot resolve reference to bean 'sessionFactory' while setting bean property 'sessionFactory'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sessionFactory' defined in class path resource [applicationContext-hibernate.xml]: Invocation of init method failed; nested exception is java.lang.OutOfMemoryError: Java heap space
    at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveReference(BeanDefinitionValueResolver.java:328)
    at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveValueIfNecessary(BeanDefinitionValueResolver.java:106)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyPropertyValues(AbstractAutowireCapableBeanFactory.java:1325)

해결법

  1. ==============================

    1.메시지는 실제로 매우 명확합니다. 뭔가가 org.apache.axis.MessageContext 유형의 값을 가진 ThreadLocal을 만듭니다. 이것은 훌륭한 힌트입니다. 이것은 아마도 Apache Axis 프레임 워크가 자체적으로 정리를 잊어 버렸거나 실패한 것을 의미합니다. Logback에서 같은 문제가 발생했습니다. 많이 신경 쓰지 말고 Axis 팀에 버그를보고하는 것이 좋습니다.

    메시지는 실제로 매우 명확합니다. 뭔가가 org.apache.axis.MessageContext 유형의 값을 가진 ThreadLocal을 만듭니다. 이것은 훌륭한 힌트입니다. 이것은 아마도 Apache Axis 프레임 워크가 자체적으로 정리를 잊어 버렸거나 실패한 것을 의미합니다. Logback에서 같은 문제가 발생했습니다. 많이 신경 쓰지 말고 Axis 팀에 버그를보고하는 것이 좋습니다.

    Tomcat은 HTTP 작업자 스레드마다 ThreadLocals이 만들어지기 때문에이 오류를보고합니다. 응용 프로그램은 배포되지 않았지만 HTTP 스레드는 남아 있습니다. 또한이 ThreadLocals도 있습니다. 이로 인해 메모리 누수 (org.apache.axis.MessageContext를 언로드 할 수 없음)와이 스레드가 나중에 재사용 될 때의 문제가 발생할 수 있습니다.

    자세한 내용은 다음을 참조하십시오. http://wiki.apache.org/tomcat/MemoryLeakProtection

  2. ==============================

    2.CDI @ApplicationScoped 빈에서 @PreDestroy 메소드에 다음을 추가했습니다. TomEE 1.6.0 (tomcat7.0.39, 오늘)을 종료하면 스레드 로컬이 지워집니다.

    CDI @ApplicationScoped 빈에서 @PreDestroy 메소드에 다음을 추가했습니다. TomEE 1.6.0 (tomcat7.0.39, 오늘)을 종료하면 스레드 로컬이 지워집니다.

    /*
     * To change this template, choose Tools | Templates
     * and open the template in the editor.
     */
    package pf;
    
    import java.lang.ref.WeakReference;
    import java.lang.reflect.Array;
    import java.lang.reflect.Field;
    
    import org.slf4j.Logger;
    import org.slf4j.LoggerFactory;
    
    /**
     *
     * @author Administrator
     * 
     * google-gson issue # 402: Memory Leak in web application; comment # 25
     * https://code.google.com/p/google-gson/issues/detail?id=402
     */
    public class ThreadLocalImmolater {
    
        final Logger logger = LoggerFactory.getLogger(ThreadLocalImmolater.class);
    
        Boolean debug;
    
        public ThreadLocalImmolater() {
            debug = true;
        }
    
        public Integer immolate() {
            int count = 0;
            try {
                final Field threadLocalsField = Thread.class.getDeclaredField("threadLocals");
                threadLocalsField.setAccessible(true);
                final Field inheritableThreadLocalsField = Thread.class.getDeclaredField("inheritableThreadLocals");
                inheritableThreadLocalsField.setAccessible(true);
                for (final Thread thread : Thread.getAllStackTraces().keySet()) {
                        count += clear(threadLocalsField.get(thread));
                        count += clear(inheritableThreadLocalsField.get(thread));
                }
                logger.info("immolated " + count + " values in ThreadLocals");
            } catch (Exception e) {
                throw new Error("ThreadLocalImmolater.immolate()", e);
            }
            return count;
        }
    
        private int clear(final Object threadLocalMap) throws Exception {
            if (threadLocalMap == null)
                    return 0;
            int count = 0;
            final Field tableField = threadLocalMap.getClass().getDeclaredField("table");
            tableField.setAccessible(true);
            final Object table = tableField.get(threadLocalMap);
            for (int i = 0, length = Array.getLength(table); i < length; ++i) {
                final Object entry = Array.get(table, i);
                if (entry != null) {
                    final Object threadLocal = ((WeakReference)entry).get();
                    if (threadLocal != null) {
                        log(i, threadLocal);
                        Array.set(table, i, null);
                        ++count;
                    }
                }
            }
            return count;
        }
    
        private void log(int i, final Object threadLocal) {
            if (!debug) {
                return;
            }
            if (threadLocal.getClass() != null &&
                threadLocal.getClass().getEnclosingClass() != null &&
                threadLocal.getClass().getEnclosingClass().getName() != null) {
    
                logger.info("threadLocalMap(" + i + "): " +
                            threadLocal.getClass().getEnclosingClass().getName());
            }
            else if (threadLocal.getClass() != null &&
                     threadLocal.getClass().getName() != null) {
                logger.info("threadLocalMap(" + i + "): " + threadLocal.getClass().getName());
            }
            else {
                logger.info("threadLocalMap(" + i + "): cannot identify threadlocal class name");
            }
        }
    
    }
    
  3. ==============================

    3."트랜잭션 자원"키는 적절한 트랜잭션없이 데이터베이스와 대화하는 것처럼 보입니다. 트랜잭션 관리가 올바르게 설정되고 @Transactional 어노테이션에서 실행되지 않는 DAO에 대한 호출 경로가 존재하지 않는지 확인하십시오. 이는 컨트롤러 레벨에서 트랜잭션 관리를 구성했지만 타이머에서 DAO를 호출하거나 @PostConstruct 주석을 사용하는 경우에 쉽게 발생할 수 있습니다. 나는 여기에 그것을 썼다 http://georgovassilis.blogspot.nl/2014/01/tomcat-spring-and-memory-leaks-when.html

    "트랜잭션 자원"키는 적절한 트랜잭션없이 데이터베이스와 대화하는 것처럼 보입니다. 트랜잭션 관리가 올바르게 설정되고 @Transactional 어노테이션에서 실행되지 않는 DAO에 대한 호출 경로가 존재하지 않는지 확인하십시오. 이는 컨트롤러 레벨에서 트랜잭션 관리를 구성했지만 타이머에서 DAO를 호출하거나 @PostConstruct 주석을 사용하는 경우에 쉽게 발생할 수 있습니다. 나는 여기에 그것을 썼다 http://georgovassilis.blogspot.nl/2014/01/tomcat-spring-and-memory-leaks-when.html

    편집 : 이것은 (또한?) v1.4.3으로 수정 된 spring-data-jpa 버그입니다. "Transactional Resources"키를 설정하는 LockModeRepositoryPostProcessor의 spring-data-jpa 소스에서 찾았습니다. 1.4.3에서는 키를 다시 지 웁니다.

  4. ==============================

    4.때때로 이것은 구성 변경과 관련이 있습니다. Tomncat 6.0.14에서 6.0.26으로 업그레이드했을 때 우리는 비슷한 것을 보았습니다. 여기 해결책이있다. http://www.skill-guru.com/blog/2010/08/22/tomcat-6-0-26-shutdown-reports-a-web-application-created-a-threadlocal-threadlocal-has-been- 강제 제거 /

    때때로 이것은 구성 변경과 관련이 있습니다. Tomncat 6.0.14에서 6.0.26으로 업그레이드했을 때 우리는 비슷한 것을 보았습니다. 여기 해결책이있다. http://www.skill-guru.com/blog/2010/08/22/tomcat-6-0-26-shutdown-reports-a-web-application-created-a-threadlocal-threadlocal-has-been- 강제 제거 /

  5. ==============================

    5.이 문제는 정리 작업에 처리기를 사용하지 않고 타사 솔루션을 사용하는 경우 나타납니다. 나를 위해 이것은 EhCache를 위해 일어났습니다. 우리는 캐싱을 위해 프로젝트에서 EhCache를 사용하고있었습니다. 그리고 종종 로그에서 다음과 같은 오류를 보곤했습니다.

    이 문제는 정리 작업에 처리기를 사용하지 않고 타사 솔루션을 사용하는 경우 나타납니다. 나를 위해 이것은 EhCache를 위해 일어났습니다. 우리는 캐싱을 위해 프로젝트에서 EhCache를 사용하고있었습니다. 그리고 종종 로그에서 다음과 같은 오류를 보곤했습니다.

     SEVERE: The web application [/products] appears to have started a thread named [products_default_cache_configuration] but has failed to stop it. This is very likely to create a memory leak.
    Aug 07, 2017 11:08:36 AM org.apache.catalina.loader.WebappClassLoader clearReferencesThreads
    SEVERE: The web application [/products] appears to have started a thread named [Statistics Thread-products_default_cache_configuration-1] but has failed to stop it. This is very likely to create a memory leak.
    

    그리고 우리는 종종 우리가 변화를 반영하고 변경 사항 반영을 위해 여러 번 응용 프로그램을 배포하는 데 사용되는 개발 중 OutOfMemory 오류로 인해 Tomcat이 실패한 것으로 나타났습니다.

    이것이 우리가 한 수정입니다.

    <listener>
      <listener-class>
         net.sf.ehcache.constructs.web.ShutdownListener
      </listener-class>
    </listener>
    

    그래서 내가 사용하려고하는 타사 라이브러리의 문서를 확인하려고합니다. 그들은 시스템을 종료하는 동안 스레드를 정리하기위한 메커니즘을 제공해야합니다. 귀하의 응용 프로그램에서 사용해야합니다. 그것들에 의해 제공되지 않는 한 휠을 다시 발명 할 필요가 없습니다. 최악의 경우는 사용자 자신의 구현을 제공하는 것입니다.

    EHCache 종료에 대한 참조 http://www.ehcache.org/documentation/2.8/operations/shutdown.html

  6. from https://stackoverflow.com/questions/5292349/is-this-very-likely-to-create-a-memory-leak-in-tomcat by cc-by-sa and MIT license