| 1 |
/* |
| 2 |
* Copyright 2004-2023 H2 Group. Multiple-Licensed under the MPL 2.0, |
| 3 |
* and the EPL 1.0 (https://h2database.com/html/license.html). |
| 4 |
* Initial Developer: Christian d'Heureuse, www.source-code.biz |
| 5 |
* |
| 6 |
* This class is multi-licensed under LGPL, MPL 2.0, and EPL 1.0. |
| 7 |
* |
| 8 |
* This module is free software: you can redistribute it and/or |
| 9 |
* modify it under the terms of the GNU Lesser General Public |
| 10 |
* License as published by the Free Software Foundation, either |
| 11 |
* version 3 of the License, or (at your option) any later version. |
| 12 |
* See https://www.gnu.org/licenses/lgpl-3.0.html |
| 13 |
* |
| 14 |
* This program is distributed in the hope that it will be useful, |
| 15 |
* but WITHOUT ANY WARRANTY; without even the implied |
| 16 |
* warranty of MERCHANTABILITY or FITNESS FOR A |
| 17 |
* PARTICULAR PURPOSE. See the GNU Lesser General Public |
| 18 |
* License for more details. |
| 19 |
*/ |
| 20 |
package org.h2.jdbcx; |
| 21 |
|
| 22 |
import java.io.PrintWriter; |
| 23 |
import java.sql.Connection; |
| 24 |
import java.sql.SQLException; |
| 25 |
import java.util.Queue; |
| 26 |
import java.util.concurrent.ConcurrentLinkedQueue; |
| 27 |
import java.util.concurrent.atomic.AtomicBoolean; |
| 28 |
import java.util.concurrent.atomic.AtomicInteger; |
| 29 |
import java.util.logging.Logger; |
| 30 |
|
| 31 |
import javax.sql.ConnectionEvent; |
| 32 |
import javax.sql.ConnectionEventListener; |
| 33 |
import javax.sql.ConnectionPoolDataSource; |
| 34 |
import javax.sql.DataSource; |
| 35 |
import javax.sql.PooledConnection; |
| 36 |
|
| 37 |
import org.h2.message.DbException; |
| 38 |
|
| 39 |
/** |
| 40 |
* A simple standalone JDBC connection pool. |
| 41 |
* It is based on the |
| 42 |
* <a href="http://www.source-code.biz/snippets/java/8.htm"> |
| 43 |
* MiniConnectionPoolManager written by Christian d'Heureuse (Java 1.5) |
| 44 |
* </a>. It is used as follows: |
| 45 |
* <pre> |
| 46 |
* import java.sql.*; |
| 47 |
* import org.h2.jdbcx.JdbcConnectionPool; |
| 48 |
* public class Test { |
| 49 |
* public static void main(String... args) throws Exception { |
| 50 |
* JdbcConnectionPool cp = JdbcConnectionPool.create( |
| 51 |
* "jdbc:h2:~/test", "sa", "sa"); |
| 52 |
* for (String sql : args) { |
| 53 |
* Connection conn = cp.getConnection(); |
| 54 |
* conn.createStatement().execute(sql); |
| 55 |
* conn.close(); |
| 56 |
* } |
| 57 |
* cp.dispose(); |
| 58 |
* } |
| 59 |
* } |
| 60 |
* </pre> |
| 61 |
* |
| 62 |
* @author Christian d'Heureuse |
| 63 |
* (<a href="http://www.source-code.biz">www.source-code.biz</a>) |
| 64 |
* @author Thomas Mueller |
| 65 |
*/ |
| 66 |
public final class JdbcConnectionPool |
| 67 |
implements DataSource, ConnectionEventListener, JdbcConnectionPoolBackwardsCompat { |
| 68 |
|
| 69 |
private static final int DEFAULT_TIMEOUT = 30; |
| 70 |
private static final int DEFAULT_MAX_CONNECTIONS = 10; |
| 71 |
|
| 72 |
private final ConnectionPoolDataSource dataSource; |
| 73 |
private final Queue<PooledConnection> recycledConnections = new ConcurrentLinkedQueue<>(); |
| 74 |
private PrintWriter logWriter; |
| 75 |
private volatile int maxConnections = DEFAULT_MAX_CONNECTIONS; |
| 76 |
private volatile int timeout = DEFAULT_TIMEOUT; |
| 77 |
private AtomicInteger activeConnections = new AtomicInteger(); |
| 78 |
private AtomicBoolean isDisposed = new AtomicBoolean(); |
| 79 |
|
| 80 |
private JdbcConnectionPool(ConnectionPoolDataSource dataSource) { |
| 81 |
this.dataSource = dataSource; |
| 82 |
if (dataSource != null) { |
| 83 |
try { |
| 84 |
logWriter = dataSource.getLogWriter(); |
| 85 |
} catch (SQLException e) { |
| 86 |
// ignore |
| 87 |
} |
| 88 |
} |
| 89 |
} |
| 90 |
|
| 91 |
/** |
| 92 |
* Constructs a new connection pool. |
| 93 |
* |
| 94 |
* @param dataSource the data source to create connections |
| 95 |
* @return the connection pool |
| 96 |
*/ |
| 97 |
public static JdbcConnectionPool create(ConnectionPoolDataSource dataSource) { |
| 98 |
return new JdbcConnectionPool(dataSource); |
| 99 |
} |
| 100 |
|
| 101 |
/** |
| 102 |
* Constructs a new connection pool for H2 databases. |
| 103 |
* |
| 104 |
* @param url the database URL of the H2 connection |
| 105 |
* @param user the user name |
| 106 |
* @param password the password |
| 107 |
* @return the connection pool |
| 108 |
*/ |
| 109 |
public static JdbcConnectionPool create(String url, String user, |
| 110 |
String password) { |
| 111 |
JdbcDataSource ds = new JdbcDataSource(); |
| 112 |
ds.setURL(url); |
| 113 |
ds.setUser(user); |
| 114 |
ds.setPassword(password); |
| 115 |
return new JdbcConnectionPool(ds); |
| 116 |
} |
| 117 |
|
| 118 |
/** |
| 119 |
* Sets the maximum number of connections to use from now on. |
| 120 |
* The default value is 10 connections. |
| 121 |
* |
| 122 |
* @param max the maximum number of connections |
| 123 |
*/ |
| 124 |
public void setMaxConnections(int max) { |
| 125 |
if (max < 1) { |
| 126 |
throw new IllegalArgumentException("Invalid maxConnections value: " + max); |
| 127 |
} |
| 128 |
this.maxConnections = max; |
| 129 |
} |
| 130 |
|
| 131 |
/** |
| 132 |
* Gets the maximum number of connections to use. |
| 133 |
* |
| 134 |
* @return the max the maximum number of connections |
| 135 |
*/ |
| 136 |
public int getMaxConnections() { |
| 137 |
return maxConnections; |
| 138 |
} |
| 139 |
|
| 140 |
/** |
| 141 |
* Gets the maximum time in seconds to wait for a free connection. |
| 142 |
* |
| 143 |
* @return the timeout in seconds |
| 144 |
*/ |
| 145 |
@Override |
| 146 |
public int getLoginTimeout() { |
| 147 |
return timeout; |
| 148 |
} |
| 149 |
|
| 150 |
/** |
| 151 |
* Sets the maximum time in seconds to wait for a free connection. |
| 152 |
* The default timeout is 30 seconds. Calling this method with the |
| 153 |
* value 0 will set the timeout to the default value. |
| 154 |
* |
| 155 |
* @param seconds the timeout, 0 meaning the default |
| 156 |
*/ |
| 157 |
@Override |
| 158 |
public void setLoginTimeout(int seconds) { |
| 159 |
if (seconds == 0) { |
| 160 |
seconds = DEFAULT_TIMEOUT; |
| 161 |
} |
| 162 |
this.timeout = seconds; |
| 163 |
} |
| 164 |
|
| 165 |
/** |
| 166 |
* Closes all unused pooled connections. |
| 167 |
* Exceptions while closing are written to the log stream (if set). |
| 168 |
*/ |
| 169 |
public void dispose() { |
| 170 |
isDisposed.set(true); |
| 171 |
|
| 172 |
PooledConnection pc; |
| 173 |
while ((pc = recycledConnections.poll()) != null) { |
| 174 |
closeConnection(pc); |
| 175 |
} |
| 176 |
} |
| 177 |
|
| 178 |
/** |
| 179 |
* Retrieves a connection from the connection pool. If |
| 180 |
* <code>maxConnections</code> connections are already in use, the method |
| 181 |
* waits until a connection becomes available or <code>timeout</code> |
| 182 |
* seconds elapsed. When the application is finished using the connection, |
| 183 |
* it must close it in order to return it to the pool. |
| 184 |
* If no connection becomes available within the given timeout, an exception |
| 185 |
* with SQL state 08001 and vendor code 8001 is thrown. |
| 186 |
* |
| 187 |
* @return a new Connection object. |
| 188 |
* @throws SQLException when a new connection could not be established, |
| 189 |
* or a timeout occurred |
| 190 |
*/ |
| 191 |
@Override |
| 192 |
public Connection getConnection() throws SQLException { |
| 193 |
long max = System.nanoTime() + timeout * 1_000_000_000L; |
| 194 |
int spin = 0; |
| 195 |
do { |
| 196 |
if (activeConnections.incrementAndGet() <= maxConnections) { |
| 197 |
try { |
| 198 |
return getConnectionNow(); |
| 199 |
} catch (Throwable t) { |
| 200 |
activeConnections.decrementAndGet(); |
| 201 |
throw t; |
| 202 |
} |
| 203 |
} else { |
| 204 |
activeConnections.decrementAndGet(); |
| 205 |
} |
| 206 |
if (--spin >= 0) { |
| 207 |
continue; |
| 208 |
} |
| 209 |
try { |
| 210 |
spin = 3; |
| 211 |
Thread.sleep(1); |
| 212 |
} catch (InterruptedException e) { |
| 213 |
Thread.currentThread().interrupt(); |
| 214 |
} |
| 215 |
} while (System.nanoTime() - max <= 0); |
| 216 |
throw new SQLException("Login timeout", "08001", 8001); |
| 217 |
} |
| 218 |
|
| 219 |
/** |
| 220 |
* INTERNAL |
| 221 |
*/ |
| 222 |
@Override |
| 223 |
public Connection getConnection(String user, String password) { |
| 224 |
throw new UnsupportedOperationException(); |
| 225 |
} |
| 226 |
|
| 227 |
private Connection getConnectionNow() throws SQLException { |
| 228 |
if (isDisposed.get()) { |
| 229 |
throw new IllegalStateException("Connection pool has been disposed."); |
| 230 |
} |
| 231 |
PooledConnection pc = recycledConnections.poll(); |
| 232 |
if (pc == null) { |
| 233 |
pc = dataSource.getPooledConnection(); |
| 234 |
} |
| 235 |
Connection conn = pc.getConnection(); |
| 236 |
pc.addConnectionEventListener(this); |
| 237 |
return conn; |
| 238 |
} |
| 239 |
|
| 240 |
/** |
| 241 |
* This method usually puts the connection back into the pool. There are |
| 242 |
* some exceptions: if the pool is disposed, the connection is disposed as |
| 243 |
* well. If the pool is full, the connection is closed. |
| 244 |
* |
| 245 |
* @param pc the pooled connection |
| 246 |
*/ |
| 247 |
private void recycleConnection(PooledConnection pc) { |
| 248 |
int active = activeConnections.decrementAndGet(); |
| 249 |
if (active < 0) { |
| 250 |
activeConnections.incrementAndGet(); |
| 251 |
throw new AssertionError(); |
| 252 |
} |
| 253 |
if (!isDisposed.get() && active < maxConnections) { |
| 254 |
recycledConnections.add(pc); |
| 255 |
if (isDisposed.get()) { |
| 256 |
dispose(); |
| 257 |
} |
| 258 |
} else { |
| 259 |
closeConnection(pc); |
| 260 |
} |
| 261 |
} |
| 262 |
|
| 263 |
private void closeConnection(PooledConnection pc) { |
| 264 |
try { |
| 265 |
pc.close(); |
| 266 |
} catch (SQLException e) { |
| 267 |
if (logWriter != null) { |
| 268 |
e.printStackTrace(logWriter); |
| 269 |
} |
| 270 |
} |
| 271 |
} |
| 272 |
|
| 273 |
/** |
| 274 |
* INTERNAL |
| 275 |
*/ |
| 276 |
@Override |
| 277 |
public void connectionClosed(ConnectionEvent event) { |
| 278 |
PooledConnection pc = (PooledConnection) event.getSource(); |
| 279 |
pc.removeConnectionEventListener(this); |
| 280 |
recycleConnection(pc); |
| 281 |
} |
| 282 |
|
| 283 |
/** |
| 284 |
* INTERNAL |
| 285 |
*/ |
| 286 |
@Override |
| 287 |
public void connectionErrorOccurred(ConnectionEvent event) { |
| 288 |
// not used |
| 289 |
} |
| 290 |
|
| 291 |
/** |
| 292 |
* Returns the number of active (open) connections of this pool. This is the |
| 293 |
* number of <code>Connection</code> objects that have been issued by |
| 294 |
* getConnection() for which <code>Connection.close()</code> has |
| 295 |
* not yet been called. |
| 296 |
* |
| 297 |
* @return the number of active connections. |
| 298 |
*/ |
| 299 |
public int getActiveConnections() { |
| 300 |
return activeConnections.get(); |
| 301 |
} |
| 302 |
|
| 303 |
/** |
| 304 |
* INTERNAL |
| 305 |
*/ |
| 306 |
@Override |
| 307 |
public PrintWriter getLogWriter() { |
| 308 |
return logWriter; |
| 309 |
} |
| 310 |
|
| 311 |
/** |
| 312 |
* INTERNAL |
| 313 |
*/ |
| 314 |
@Override |
| 315 |
public void setLogWriter(PrintWriter logWriter) { |
| 316 |
this.logWriter = logWriter; |
| 317 |
} |
| 318 |
|
| 319 |
/** |
| 320 |
* Return an object of this class if possible. |
| 321 |
* |
| 322 |
* @param iface the class |
| 323 |
* @return this |
| 324 |
*/ |
| 325 |
@Override |
| 326 |
@SuppressWarnings("unchecked") |
| 327 |
public <T> T unwrap(Class<T> iface) throws SQLException { |
| 328 |
try { |
| 329 |
if (isWrapperFor(iface)) { |
| 330 |
return (T) this; |
| 331 |
} |
| 332 |
throw DbException.getInvalidValueException("iface", iface); |
| 333 |
} catch (Exception e) { |
| 334 |
throw DbException.toSQLException(e); |
| 335 |
} |
| 336 |
} |
| 337 |
|
| 338 |
/** |
| 339 |
* Checks if unwrap can return an object of this class. |
| 340 |
* |
| 341 |
* @param iface the class |
| 342 |
* @return whether or not the interface is assignable from this class |
| 343 |
*/ |
| 344 |
@Override |
| 345 |
public boolean isWrapperFor(Class<?> iface) throws SQLException { |
| 346 |
return iface != null && iface.isAssignableFrom(getClass()); |
| 347 |
} |
| 348 |
|
| 349 |
/** |
| 350 |
* [Not supported] |
| 351 |
*/ |
| 352 |
@Override |
| 353 |
public Logger getParentLogger() { |
| 354 |
return null; |
| 355 |
} |
| 356 |
|
| 357 |
|
| 358 |
} |