I use ExecutorService with FixedThreadPool to execute some SQL via JDBC. However when I profile my app it seems that thread count is just raising and so does the memory of course. The problem is that is is somehow related to JDBC because when I remove creating statements and connections inside my task for the thread pool, the thread count is not raising at all.
Here is how I sumbit tasks into my thread pool:
new Thread() {
public void run() {
ExecutorService executorService = Executors.newFixedThreadPool(5);
while (!isCancelled) {
executorService.submit(RunnableTask.this);
Thread.sleep(interval);
}
executorService.shutdown(); //wait for all tasks to finish and then shutdown executor
executorService.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS); //wait till shutdown finished
} catch (InterruptedException ex) {
//
}
}
};
Here is what I do in the task:
try (Connection con = pool.getConnection(); PreparedStatement st = (this.isCall ? con.prepareCall(this.sql) : con.prepareStatement(this.sql))) {
st.execute();
} catch (Exception e) {
//
}
Here is the ConnectionPool, that is used in above mentioned code (pool.getConnection(), I use apache DBCP2:
import java.sql.Connection;
import java.sql.SQLException;
import org.apache.commons.dbcp2.BasicDataSource;
public class MySQLPool {
private BasicDataSource dataSource;
public MySQLPool setup(String driver, String uri, String user, String password, int maxConnections) throws Exception {
if (this.dataSource == null) {
BasicDataSource ds = new BasicDataSource();
ds.setDriverClassName(Main.driver);
ds.setUrl(uri);
ds.setUsername(user);
ds.setPassword(password);
ds.setMaxTotal(maxConnections);
ds.setMaxWaitMillis(2000);
this.dataSource = ds;
}
return this;
}
Here is a example from profiler (imgur)
It seems that the threads are not ended properly, which is very weird because the ExecutorService should run out of them if it is a fixed pool of 5 connections right ? So I have no idea how the hreads are still there, they are causing quite large memory leak.
The problem is in creating Connection and PreparedStatement objects because when I comment it out, the number of threads stays at a fixed value.