I am getting memory leak error for transferManager thread for Amazons3Client.
WARNING [Thread-7] org.apache.catalina.loader.WebappClassLoaderBase.clearReferencesThreads The web application [ROOT] appears to have started a thread named [s3-transfer-manager-worker-1] but has failed to stop it. This is very likely to create a memory leak. Stack trace of thread:
We have a class which has Amazons3Client and TransferManager object defined as static and protected and initialized it in static block.
public class Testing implements StoredFileStrategy{
protected static AmazonS3Client s3;
protected static TransferManager xferMgr;
static {
ClasspathPropertiesFileCredentialsProvider provider = new ClasspathPropertiesFileCredentialsProvider();
s3 = new AmazonS3Client(new ClasspathPropertiesFileCredentialsProvider());
s3.setRegion(Region.getRegion(getRegionName()));
xferMgr = new TransferManager(s3);
}
public static void shutdownTransferManager(){
xferMgr.shutdownNow();
}
}
There is another class that has contextDestroyed method show as below:
@WebListener
public class AppContextListener implements ServletContextListener
{
@Override
public void contextInitialized(ServletContextEvent servletContextEvent) {
//...some code
}
@Override
public void contextDestroyed(ServletContextEvent servletContextEvent) {
try {
com.mysql.cj.jdbc.AbandonedConnectionCleanupThread.checkedShutdown();
com.amazonaws.http.IdleConnectionReaper.shutdown();
S3StoredFileStrategy.shutdownTransferManager();
// Thread.sleep(3000);
} catch (Throwable ex) {
ex.printStackTrace();
logger.error(Common.getExceptionMessage(ex));
}
}
So I made a method in that class that calls shutdown() on trasfermanager object. This object is called from contextDestroyed method. But still memoryLeak error on tomcat close is appearing.
I debugged the code and then added a Thread.sleep() method for 3 second in contextDestroyed method after shutdown call. Then memory leak message disappears. So If I uncomment the above code of thread.sleep() resources is shutting down properly and not giving error of memory leak.But I don't know Why this is working after calling sleep method. And how safe it is to call sleep method in contextDestroyed? I have multiple threads(Timer, JDBC, etc..) that is giving error of memory leak.
When we stop tomcat all thread will get destroyed but this memory leak threads will not destroy? How should I check that? As jprofiler will only show threads till the time tomcat is running.
Any help is appreciated. Thank you in advance.