Answer the question
In order to leave comments, you need to log in
Is it possible to use try with resources to close a connection from a pool?
I am fairly new to java. There was a misunderstanding in terms of the correct release of the connection taken from the pool. I use try with resources, but more experienced colleagues say that this is not the way to close, since this will lead to the fact that all connections from the pool will be used up.
Code example:
public void saveUser(User user) {
try (
Connection connection = connectionPool.getConnection();
PreparedStatement preparedStatement = connection.prepareStatement(
"INSERT INTO users (id, login, pass) VALUES (nextval('sqn_user'),?,?)")) {
preparedStatement.setString(1, user.getUserLogin());
preparedStatement.setString(2, user.getUserPass());
preparedStatement.execute();
connection.commit();
} catch (SQLException e) {
log.error(e);
}
}
HikariDataSource dataSource;
HikariConfig config = new HikariConfig();
config.setDriverClassName("org.postgresql.Driver");
config.set...url,username,password;
config.setAutoCommit(false);
config.setMaximumPoolSize(50);
dataSource = new HikariDataSource(config);
dataSource.setInitializationFailFast(true);
Answer the question
In order to leave comments, you need to log in
Yes, you can. Everything that inherits the AutoCloseable interface can be used in try-with-resources.
You need to look at what kind of "connectionPool" it is... If it is a DatSource implementation, for example, obtained from a tomcat, or org.apache.commons.dbcp.BasicDataSource... Then the method call close will return the connection back to the pool. And if a person somehow works directly with the pool, then you need to hit on the hands
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question