springbootservletinitializer servlet deploy app spring apache tomcat

spring - servlet - ¿Es muy probable que esto genere una pérdida de memoria en Tomcat?



war spring boot web xml (5)

Configuré Tomcat para trabajar con una fuente abierta externa diferente.

Sin embargo, después de que el gato se ejecuta por unos minutos, obtengo:

SEVERE: La aplicación web [/ MyProject] creó un ThreadLocal con la clave de tipo [java.lang.ThreadLocal] (value [java.lang.ThreadLocal@1b3f02f]) y un valor de tipo [org.apache.axis.MessageContext] ( value [org.apache.axis.MessageContext@5dbd4e]) pero no pudo eliminarlo cuando se detuvo la aplicación web. Esto es muy probable que cree una pérdida de memoria.

¿Qué podría causarlo?

¿Dónde debo mirar? ¿Podría ser una combinación de datos en Tomcat?

¿Y qué significa Hilos en Tomcat?

EDITADO

Aquí está mi rastro completo. La aplicación parece volver a cargar su contexto mientras aún se está ejecutando, ¡y no sé por qué!

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)



Agregué lo siguiente al método @PreDestroy en mi bean CDI @ApplicationScoped, y cuando cerré TomEE 1.6.0 (tomcat7.0.39, a partir de hoy), borra los locales del hilo.

/* * 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"); } } }


El mensaje es bastante claro: algo crea un ThreadLocal con el valor de tipo org.apache.axis.MessageContext : esta es una gran pista. Lo más probable es que el marco de Apache Axis olvidó / no pudo limpiar después de sí mismo. El mismo problem ocurrió, por ejemplo, en Logback. No deberías molestarte demasiado, pero reportar una falla al equipo de Axis podría ser una buena idea.

Tomcat informa este error porque los ThreadLocal s se crean por hilos de trabajo HTTP. Su aplicación no está desplegada, pero los hilos HTTP permanecen, y también estos ThreadLocal . Esto puede provocar fugas de memoria (no se puede descargar org.apache.axis.MessageContext ) y algunos problemas cuando estos subprocesos se reutilicen en el futuro.

Para detalles, ver: http://wiki.apache.org/tomcat/MemoryLeakProtection


Este problema aparece cuando utilizamos una solución de terceros, sin utilizar los controladores para la actividad de limpieza. Para mí esto estaba sucediendo para EhCache. Estábamos usando EhCache en nuestro proyecto para el almacenamiento en caché. Y a menudo solíamos ver el siguiente error en los registros

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.

Y a menudo notamos que tomcat falló por el error OutOfMemory durante el desarrollo en el que solíamos hacer cambios en el servidor y desplegar la aplicación varias veces para reflejar nuestros cambios.

Esta es la solución que hicimos

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

El punto que trato de hacer es verificar la documentación de las bibliotecas de terceros que está utilizando. Deben proporcionar algunos mecanismos para limpiar los hilos durante el cierre. Que debes usar en tu aplicación. No es necesario volver a inventar la rueda a menos que no sea proporcionada por ellos. El peor caso es proporcionar su propia implementación.

Referencia para EHCache Shutdown http://www.ehcache.org/documentation/2.8/operations/shutdown.html


La clave "Recursos transaccionales" parece que está hablando con la base de datos sin una transacción adecuada. Asegúrese de que la gestión de transacciones esté configurada correctamente y que no exista una ruta de invocación al DAO que no se ejecute bajo una anotación @Transactional. Esto puede suceder fácilmente cuando configura la gestión de transacciones en el nivel del Controlador, pero está invocando DAO en un temporizador o está utilizando anotaciones de @PostConstruct. Lo escribí aquí http://georgovassilis.blogspot.nl/2014/01/tomcat-spring-and-memory-leaks-when.html

Editar: Parece que esto es (¿también?) Un error con spring-data-jpa que se ha corregido con v1.4.3. Lo busqué en las fuentes spring-data-jpa de LockModeRepositoryPostProcessor que establece la clave "Recursos transaccionales". En 1.4.3, también borra la clave nuevamente.