1

i have a web service that uses javax.sql.DataSource as follows:

public class AccessMysql {

 private static DataSource dataSource=null;

    public  AccessMysql(){
      if (dataSource == null){
        dataSource = DataSourceBuilder
                .create()
                .username("[username]")
                .password("[password]")
                .url("jdbc:mysql://[server]/testdb")
                .driverClassName("com.mysql.jdbc.Driver")
                .build();
      }
    }
...
}

The first time this class runs the following mysql command:

show processlist

shows 11 connections.

The service can access the database numerous times and my number of connections (as shown in via 'show processlist') consistently stays at 11.

Do these 11 connections ever go away on their own? Is there any way I can close them from Java?

Xstian
  • 8,184
  • 10
  • 42
  • 72
Mark Juszczec
  • 85
  • 1
  • 2
  • 7

1 Answers1

0

If you check the code of the DataSourceBuilder, you will see that if it has got no specific instruction from you, it will create a pooled datasource (type varies based on the available classes on the classpath):

private static final String[] DATA_SOURCE_TYPE_NAMES = new String[] {
        "org.apache.tomcat.jdbc.pool.DataSource",
        "com.zaxxer.hikari.HikariDataSource",
        "org.apache.commons.dbcp.BasicDataSource" };

These pooled datasource will keep open an X (in your case probably 10) number of connections to save time on opening new connections when needed. This is the concept of connection-pooling.

Gergely Bacso
  • 14,243
  • 2
  • 44
  • 64
  • understood. so the service has 10 open connections ready in case they are needed. is there a way to set a timeout so if they are inactive for X minutes they'll be torn down? – Mark Juszczec Dec 04 '15 at 14:56
  • Yes, of course. In that case however you need to configure things by hand, instead of leaving it to Spring autoconfigure. Pick a pooling solution you like and configure it accordingly. Take a look at this: http://stackoverflow.com/questions/25573034/spring-boot-how-do-i-set-jdbc-pool-properties-like-maximum-number-of-connection – Gergely Bacso Dec 04 '15 at 15:53