2011-03-13 27 views
44

Configuré tomcat para que funcione con una fuente abierta externa diferente.¿Es muy probable que esto genere una pérdida de memoria en Tomcat?

Sin embargo, después de que el gato está en marcha durante unos minutos me sale:

GRAVES: La aplicación web [/ MiProyecto] creó un ThreadLocal con clave del tipo [java.lang.ThreadLocal] (valor [[email protected]]) y un valor de tipo [org.apache.axis.MessageContext] (valor [[email protected]]) pero no se pudo eliminar cuando la Web la aplicación fue detenida 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í es mi traza completa. 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 [[email protected]]) and a value of type [org.mvel2.debug.DebuggerContext] (value [[email protected]]) 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 [[email protected]]) and a value of type [com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderImpl] (value [[email protected]cfa]) 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 [[email protected]]) 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 [[email protected]]) and a value of type [org.apache.axis.MessageContext] (value [[email protected]]) 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 [[email protected]]) and a value of type [com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderImpl] (value [[email protected]84]) 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 [{[email protected][email protected]}]) 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 [[email protected]]) and a value of type [com.sun.faces.application.ApplicationAssociate] (value [[email protected]]) 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) 

Respuesta

23

El mensaje es bastante claro: algo crea una ThreadLocal con 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 de este error porque ThreadLocal s se crean por subprocesos de trabajo HTTP. Su aplicación no está desplegada, pero los hilos HTTP permanecen, y estos ThreadLocal s también. Esto puede provocar pérdidas de memoria (org.apache.axis.MessageContext no se puede descargar) y algunos problemas cuando estos subprocesos se reutilizan en el futuro.

Para más detalles ver: http://wiki.apache.org/tomcat/MemoryLeakProtection

+0

gracias I editado mi pregunta con la traza completa - Todavía no entiendo por qué va a iniciar Tomcat para recargar el contexto en el medio y por lo tanto el contexto de aplicación de la primavera falla – Dejell

+2

Son ¿Experimenta recargas de contexto inesperadas? Pocas personas [lucharon] (http://forum.springsource.org/showthread.php?t=82423) con eso. En cuanto a la pérdida de memoria, es producida por Axis, no por ti. Pero el inicio de su contexto falla con la memoria del montón, lo cual es extraño, por lo general, el PermGen se agota pronto. ¿Tal vez esta fuga de memoria 'ThreadLocal' es mucho más seria? Use '-XX: + HeapDumpOnOutOfMemoryError' para diagnosticar el problema. –

+0

en realidad para gestionar con la recarga de contexto que utilicé reloadable = "false" en tomcat . Soy consciente de que cualquier cambio en el código o las propiedades de Java me obligará a reiniciar el servidor, pero vale la pena. – Dejell

6

que añade lo siguiente al método @PreDestroy en mi CDI @ApplicationScoped frijol, y cuando el apagado TomEE 1.6.0 (tomcat7.0.39, a partir de hoy), borra los locales de rosca.

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

} 
2

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.

0

Este problema aparece cuando utilizamos una solución de terceros, sin utilizar los controladores para la actividad de limpieza. Para mí, esto estaba sucediendo en EhCache. Estábamos usando EhCache en nuestro proyecto para el almacenamiento en caché. Y a menudo estábamos acostumbrados a ver después de 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 nos dimos cuenta de Tomcat a menudo no para el error OutOfMemory durante el desarrollo donde solíamos hacer cambios de back-end e implementar la aplicación varias veces para reflejar nuestros cambios.

Este es el arreglo que hicimos

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

Así que estoy tratando de hacer es comprobar la documentación de las bibliotecas de terceros que usted esté usando. 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 apagado http://www.ehcache.org/documentation/2.8/operations/shutdown.html

Cuestiones relacionadas