停止/重新部署应用程序时出现tomcat内存泄漏问题。它说以下Web应用程序已停止(重新加载,取消部署),但它们已经停止 以前运行的类仍然会加载到内存中,从而导致内存 泄漏(使用分析器确认):/ test-1.0-SNAPSHOT
MySQL连接器驱动程序位于Tomcat / lib文件夹中。 我可以在两者中重现这个问题:Tomcat 7/8。还尝试使用“net.sourceforge.jtds。*”驱动程序的MS SQL数据库,但没有帮助。
请在下面找到项目文件。 Project仅在DB中创建1个表。
的build.gradle
group 'com.test'
version '1.0-SNAPSHOT'
apply plugin: 'java'
apply plugin: 'war'
sourceCompatibility = 1.8
repositories {
mavenCentral()
}
dependencies {
compile group: 'org.hibernate', name: 'hibernate-entitymanager', version: '5.2.10.Final'
compile group: 'org.springframework.data', name: 'spring-data-jpa', version: '1.11.4.RELEASE'
compile group: 'org.springframework', name: 'spring-webmvc', version: '4.3.9.RELEASE'
providedCompile 'javax.servlet:javax.servlet-api:3.1.0'
providedCompile group: 'mysql', name: 'mysql-connector-java', version: '5.1.6'
compile group: 'commons-dbcp', name: 'commons-dbcp', version: '1.4'
}
ApplicationConfig.java
@Configuration
@Import({JPAConfiguration.class})
@EnableWebMvc
public class ApplicationConfig {}
JPAConfiguration.java
@Configuration
@EnableJpaRepositories("com.test.dao")
@EnableTransactionManagement
public class JPAConfiguration {
@Bean
public EntityManagerFactory entityManagerFactory() {
LocalContainerEntityManagerFactoryBean factory = new LocalContainerEntityManagerFactoryBean();
factory.setJpaVendorAdapter(new HibernateJpaVendorAdapter());
factory.setPackagesToScan("com.test.model");
factory.setDataSource(restDataSource());
factory.setJpaPropertyMap(getPropertyMap());
factory.afterPropertiesSet();
return factory.getObject();
}
@Bean(destroyMethod = "close")
public DataSource restDataSource() {
BasicDataSource dataSource = new BasicDataSource();
dataSource.setDriverClassName("com.mysql.jdbc.Driver");
dataSource.setUrl("jdbc:mysql://localhost:3306/test");
dataSource.setUsername("test");
dataSource.setPassword("test");
return dataSource;
}
private Map<String, String> getPropertyMap() {
Map<String, String> hibernateProperties = new HashMap<>();
hibernateProperties.put("hibernate.hbm2ddl.auto", "update");
hibernateProperties.put("hibernate.show_sql", "true");
hibernateProperties.put("hibernate.format_sql", "true");
hibernateProperties.put("hibernate.dialect", "org.hibernate.dialect.MySQL5InnoDBDialect");
return hibernateProperties;
}
@Bean
public PlatformTransactionManager transactionManager() {
JpaTransactionManager txManager = new JpaTransactionManager();
txManager.setEntityManagerFactory(entityManagerFactory());
return txManager;
}
}
TestRepository.java
@Repository
public interface TestRepository extends JpaRepository<TestEntity, Long> {}
TestEntity.java
@Entity
@Table(name = "ent")
public class TestEntity {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String descript;
//equals, hashcode, toString, getters, setters
}
AppInitializer.java
public class AppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
private WebApplicationContext rootContext;
@Override
protected Class<?>[] getRootConfigClasses() {
return new Class[]{ApplicationConfig.class};
}
@Override
protected Class<?>[] getServletConfigClasses() {
return null;
}
@Override
protected String[] getServletMappings() {
return new String[]{"/"};
}
}
命令
jmap -histo <tomcat_pid>
在tomcat停止后只显示项目结构中的2个项目:
com.test.config.dao.JPAConfiguration$$EnhancerBySpringCGLIB$$792cb231$$FastClassBySpringCGLIB$$45ff499c
com.test.config.dao.JPAConfiguration$$FastClassBySpringCGLIB$$10104c1e
任何人都有解决此问题的想法或建议吗?
答案 0 :(得分:5)
这个小项目有2个内存泄漏:
我们必须添加ContextLoaderListener
来注销jdbc驱动程序:
监听器:
@WebListener
public class ContextListener extends ContextLoaderListener {
private final Logger log = LoggerFactory.getLogger(this.getClass());
@Override
public void contextInitialized(ServletContextEvent sce) {
log.info("-= Context started =-");
}
@Override
public void contextDestroyed(ServletContextEvent sce) {
super.contextDestroyed(sce);
log.info("-= Context destroyed =-");
try {
log.info("Calling MySQL AbandonedConnectionCleanupThread checkedShutdown");
com.mysql.cj.jdbc.AbandonedConnectionCleanupThread.uncheckedShutdown();
} catch (Exception e) {
log.error("Error calling MySQL AbandonedConnectionCleanupThread checkedShutdown {}", e);
}
ClassLoader cl = Thread.currentThread().getContextClassLoader();
Enumeration<Driver> drivers = DriverManager.getDrivers();
while (drivers.hasMoreElements()) {
Driver driver = drivers.nextElement();
if (driver.getClass().getClassLoader() == cl) {
try {
log.info("Deregistering JDBC driver {}", driver);
DriverManager.deregisterDriver(driver);
} catch (SQLException ex) {
log.error("Error deregistering JDBC driver {}", driver, ex);
}
} else {
log.info("Not deregistering JDBC driver {} as it does not belong to this webapp's ClassLoader", driver);
}
}
}
}
或者如果您有权访问tomcat服务器,则可以在 tomcat / conf / server.xml example中修改监听器。
从休眠依赖项中删除该库后,内存泄漏已消失:
build.gradle:
group 'com.test'
version '1.0-SNAPSHOT'
apply plugin: 'java'
apply plugin: 'war'
sourceCompatibility = 1.8
repositories {
mavenCentral()
}
dependencies {
compile(group: 'org.hibernate', name: 'hibernate-entitymanager', version: '5.2.10.Final') {
exclude group: 'org.jboss.logging', module: 'jboss-logging'
}
compile group: 'org.springframework.data', name: 'spring-data-jpa', version: '1.11.4.RELEASE'
compile group: 'org.springframework', name: 'spring-webmvc', version: '4.3.9.RELEASE'
providedCompile 'javax.servlet:javax.servlet-api:3.1.0'
providedCompile group: 'mysql', name: 'mysql-connector-java', version: '8.0.11'
compile group: 'org.slf4j', name: 'slf4j-api', version: '1.7.25'
compile group: 'org.slf4j', name: 'slf4j-simple', version: '1.7.25'
}
然后从repo构建jar,并将其添加到tomcat / lib 文件夹中。
jboss-logging的问题可能已在Java 9(pull request link)中解决。
答案 1 :(得分:3)
简短的回答-希望您遇到同样的问题...
在MySQL中com.test.config.dao.JPAConfiguration$$...CGLIB$$...
间接引用了这两个Abandoned connection cleanup thread
类:
20-Jun-2018 21:25:22.987 WARNING [localhost-startStop-1] org.apache.catalina.loader.WebappClassLoaderBase.clearReferencesThreads The web application [test-1.0-SNAPSHOT] appears to have started a thread named [Abandoned connection cleanup thread] but has failed to stop it. This is very likely to create a memory leak. Stack trace of thread:
java.lang.Object.wait(Native Method)
java.lang.ref.ReferenceQueue.remove(ReferenceQueue.java:143)
com.mysql.cj.jdbc.AbandonedConnectionCleanupThread.run(AbandonedConnectionCleanupThread.java:43)
以下struct serialization in C and transfer over MPI使我能够解决问题。例如。在tomcat/conf/server.xml
中,找到JreMemoryLeakPreventionListener
行并将其替换为:
<Listener className="org.apache.catalina.core.JreMemoryLeakPreventionListener"
classesToInitialize="com.mysql.jdbc.Driver" />
这将强制将MySQL JDBC驱动程序及其清理线程加载到Web应用程序的类加载器之外。这意味着清除线程不会将对webapp类加载器的引用作为其上下文类加载器。
扩展的答案-如何跟踪环境中的泄漏...
希望以上就是您所需要的-足以复制并解决answer的问题
但是,有很多其他原因导致对该Web应用程序的引用泄漏,也可以阻止它取消部署。例如。其他仍在运行的线程(Tomcat擅长于警告这些线程)或Web应用程序外部的引用。
要正确跟踪原因,可以在堆转储中追踪引用。如果不熟悉,则可以从jmap -dump:file=dump.hprof <pid>
获得堆转储,也可以直接从jvisualvm
这样的连接(也包含在JDK中)获得堆转储。
在jvisualvm
中打开堆转储:
Classes
按钮com.test.config.dao.JPAConfiguration$$EnhancerBySpringCGLIB$$
在此示例中Instances View
References
窗格中,右键单击并Show Nearest GC Root
Abandoned connection cleanup thread
:
https://github.com/egotovko/tomcat-leak 请注意AbandonedConnectionCleanupThread
如何具有contextClassLoader
,即Web应用程序的ParallelWebappClassLoader
。 Tomcat需要能够释放类加载器以取消部署Web应用程序。
一旦您找到了保存引用的内容,通常就来研究在Tomcat中如何更好地配置该库,或者也许其他人看到了内存泄漏。在有多个参考文献需要清理时,重复练习也很常见。