My favorites
|
Sign in
h2database
Java SQL database
Project Home
Downloads
Wiki
Issues
Source
Checkout
|
Browse
|
Changes
|
‹r1630
r2048
Source path:
svn
/
trunk
/
h2
/
src
/
main
/
org
/
h2
/
jdbcx
/
JdbcConnectionPool.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
/*
* Copyright 2004-2009 H2 Group. Multiple-Licensed under the H2 License,
* Version 1.0, and under the Eclipse Public License, Version 1.0
* (http://h2database.com/html/license.html).
* Initial Developer: Christian d'Heureuse, www.source-code.biz
*
* This class is dual-licensed LGPL and under the H2 License.
*
* This module is free software: you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation, either
* version 3 of the License, or (at your option) any later version.
* See http://www.gnu.org/licenses/lgpl.html
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied
* warranty of MERCHANTABILITY or FITNESS FOR A
* PARTICULAR PURPOSE. See the GNU Lesser General Public
* License for more details.
*/
package org.h2.jdbcx;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Stack;
import javax.sql.ConnectionEvent;
import javax.sql.ConnectionEventListener;
import javax.sql.ConnectionPoolDataSource;
import javax.sql.DataSource;
import javax.sql.PooledConnection;
/*## Java 1.6 begin ##
import org.h2.message.Message;
## Java 1.6 end ##*/
/**
* A simple standalone JDBC connection pool.
* It is based on the
* <a href="http://www.source-code.biz/snippets/java/8.htm">
* MiniConnectionPoolManager written by Christian d'Heureuse (Java 1.5)
* </a>. It is used as follows:
* <pre>
* import java.sql.*;
* import org.h2.jdbcx.JdbcConnectionPool;
* public class Test {
* public static void main(String... args) throws Exception {
* JdbcConnectionPool cp = JdbcConnectionPool.create(
* "jdbc:h2:~/test", "sa", "sa");
* for (String sql : args) {
* Connection conn = cp.getConnection();
* conn.createStatement().execute(sql);
* conn.close();
* }
* cp.dispose();
* }
* }
* </pre>
*
* @author Christian d'Heureuse
* (<a href="http://www.source-code.biz">www.source-code.biz</a>)
* @author Thomas Mueller (ported to Java 1.4, some changes)
*/
public class JdbcConnectionPool implements DataSource {
private static final int DEFAULT_TIMEOUT = 5 * 60;
private final ConnectionPoolDataSource dataSource;
private final Stack<PooledConnection> recycledConnections = new Stack<PooledConnection>();
private final PoolConnectionEventListener poolConnectionEventListener = new PoolConnectionEventListener();
private PrintWriter logWriter;
private int maxConnections = 10;
private int timeout = DEFAULT_TIMEOUT;
private int activeConnections;
private boolean isDisposed;
private JdbcConnectionPool(ConnectionPoolDataSource dataSource) {
this.dataSource = dataSource;
try {
logWriter = dataSource.getLogWriter();
} catch (SQLException e) {
// ignore
}
}
/**
* Constructs a new connection pool.
*
* @param dataSource the data source to create connections
* @return the connection pool
*/
public static JdbcConnectionPool create(ConnectionPoolDataSource dataSource) {
return new JdbcConnectionPool(dataSource);
}
/**
* Constructs a new connection pool for H2 databases.
*
* @param url the database URL of the H2 connection
* @param user the user name
* @param password the password
* @return the connection pool
*/
public static JdbcConnectionPool create(String url, String user, String password) {
JdbcDataSource ds = new JdbcDataSource();
ds.setURL(url);
ds.setUser(user);
ds.setPassword(password);
return new JdbcConnectionPool(ds);
}
/**
* Sets the maximum number of connections to use from now on.
* The default value is 10 connections.
*
* @param max the maximum number of connections
*/
public synchronized void setMaxConnections(int max) {
if (max < 1) {
throw new IllegalArgumentException("Invalid maxConnections value: " + max);
}
this.maxConnections = max;
// notify waiting threads if the value was increased
notifyAll();
}
/**
* Gets the maximum number of connections to use.
*
* @return the max the maximum number of connections
*/
public synchronized int getMaxConnections() {
return maxConnections;
}
/**
* Gets the maximum time in seconds to wait for a free connection.
*
* @return the timeout in seconds
*/
public synchronized int getLoginTimeout() {
return timeout;
}
/**
* Sets the maximum time in seconds to wait for a free connection.
* The default timeout is 5 minutes. Calling this method with the
* value 0 will set the timeout to the default value.
*
* @param seconds the timeout, 0 meaning the default
*/
public synchronized void setLoginTimeout(int seconds) {
if (seconds == 0) {
seconds = DEFAULT_TIMEOUT;
}
this.timeout = seconds;
}
/**
* Closes all unused pooled connections.
*/
public synchronized void dispose() throws SQLException {
if (isDisposed) {
return;
}
isDisposed = true;
SQLException e = null;
while (!recycledConnections.isEmpty()) {
PooledConnection pc = recycledConnections.pop();
try {
pc.close();
} catch (SQLException e2) {
if (e == null) {
e = e2;
}
}
}
if (e != null) {
throw e;
}
}
/**
* Retrieves a connection from the connection pool. If
* <code>maxConnections</code> connections are already in use, the method
* waits until a connection becomes available or <code>timeout</code>
* seconds elapsed. When the application is finished using the connection,
* it must close it in order to return it to the pool.
* If no connection becomes available within the given timeout, an exception
* with SQL state 08001 and vendor code 8001 is thrown.
*
* @return a new Connection object.
* @throws SQLException when a new connection could not be established,
* or a timeout occurred
*/
public Connection getConnection() throws SQLException {
for (int i = 0;; i++) {
synchronized (this) {
if (activeConnections < maxConnections) {
return getConnectionNow();
}
if (i >= timeout) {
throw new SQLException("Login timeout", "08001", 8001);
}
try {
wait(1000);
} catch (InterruptedException e) {
// ignore
}
}
}
}
private Connection getConnectionNow() throws SQLException {
if (isDisposed) {
throw new IllegalStateException("Connection pool has been disposed.");
}
PooledConnection pc;
if (!recycledConnections.empty()) {
pc = recycledConnections.pop();
} else {
pc = dataSource.getPooledConnection();
}
Connection conn = pc.getConnection();
activeConnections++;
pc.addConnectionEventListener(poolConnectionEventListener);
return conn;
}
/**
* This method usually puts the connection back into the pool. There are
* some exceptions: if the pool is disposed, the connection is disposed as
* well. If the pool is full, the connection is closed.
*
* @param pc the pooled connection
*/
synchronized void recycleConnection(PooledConnection pc) {
if (isDisposed) {
disposeConnection(pc);
return;
}
if (activeConnections <= 0) {
throw new AssertionError();
}
activeConnections--;
if (activeConnections < maxConnections) {
recycledConnections.push(pc);
} else {
closeConnection(pc);
}
notifyAll();
}
private void closeConnection(PooledConnection pc) {
try {
pc.close();
} catch (SQLException e) {
log("Error while closing database connection: " + e.toString());
}
}
/**
* Close the connection, and don't add it back to the pool.
*
* @param pc the pooled connection
*/
synchronized void disposeConnection(PooledConnection pc) {
if (activeConnections <= 0) {
throw new AssertionError();
}
activeConnections--;
notifyAll();
closeConnection(pc);
}
private void log(String msg) {
String s = getClass().getName() + ": " + msg;
try {
if (logWriter == null) {
System.err.println(s);
} else {
logWriter.println(s);
}
} catch (Exception e) {
// ignore
}
}
/**
* This event listener informs the connection pool that about closed and
* broken connections.
*/
class PoolConnectionEventListener implements ConnectionEventListener {
public void connectionClosed(ConnectionEvent event) {
PooledConnection pc = (PooledConnection) event.getSource();
pc.removeConnectionEventListener(this);
recycleConnection(pc);
}
public void connectionErrorOccurred(ConnectionEvent event) {
PooledConnection pc = (PooledConnection) event.getSource();
pc.removeConnectionEventListener(this);
disposeConnection(pc);
}
}
/**
* Returns the number of active (open) connections of this pool. This is the
* number of <code>Connection</code> objects that have been issued by
* getConnection() for which <code>Connection.close()</code> has
* not yet been called.
*
* @return the number of active connections.
*/
public synchronized int getActiveConnections() {
return activeConnections;
}
/**
* INTERNAL
*/
public Connection getConnection(String username, String password) {
throw new UnsupportedOperationException();
}
/**
* INTERNAL
*/
public PrintWriter getLogWriter() {
return logWriter;
}
/**
* INTERNAL
*/
public void setLogWriter(PrintWriter logWriter) {
this.logWriter = logWriter;
}
/**
* [Not supported] Return an object of this class if possible.
*
* @param iface the class
*/
/*## Java 1.6 begin ##
public <T> T unwrap(Class<T> iface) throws SQLException {
throw Message.getUnsupportedException("unwrap");
}
## Java 1.6 end ##*/
/**
* [Not supported] Checks if unwrap can return an object of this class.
*
* @param iface the class
*/
/*## Java 1.6 begin ##
public boolean isWrapperFor(Class< ? > iface) throws SQLException {
throw Message.getUnsupportedException("isWrapperFor");
}
## Java 1.6 end ##*/
}
Show details
Hide details
Change log
r1755
by thomas.tom.mueller on Aug 17, 2009
Diff
Use varargs.
Go to:
...h2/src/docsrc/html/advanced.html
...2/src/docsrc/html/changelog.html
...h2/src/docsrc/html/features.html
.../h2/src/docsrc/html/roadmap.html
...h2/src/docsrc/html/tutorial.html
...rc/docsrc/text/_docs_en.utf8.txt
...rc/docsrc/text/_docs_ja.utf8.txt
...src/textbase/_docs_en.properties
...main/org/h2/command/Command.java
.../main/org/h2/command/Parser.java
...d/ddl/AlterTableAlterColumn.java
...2/command/dml/AlterSequence.java
...h2/compress/CompressDeflate.java
...n/org/h2/constant/ErrorCode.java
...rg/h2/engine/ConnectionInfo.java
...main/org/h2/engine/Database.java
...org/h2/engine/FunctionAlias.java
...src/main/org/h2/engine/User.java
.../org/h2/expression/Function.java
...h2/expression/TableFunction.java
...in/org/h2/fulltext/FullText.java
.../h2/fulltext/FullTextLucene.java
...in/org/h2/index/IndexCursor.java
.../main/org/h2/jdbc/JdbcArray.java
...h2/jdbcx/JdbcConnectionPool.java
...main/org/h2/message/Message.java
.../org/h2/message/TraceSystem.java
...main/org/h2/schema/Sequence.java
...org/h2/schema/TriggerObject.java
.../main/org/h2/server/Service.java
...ain/org/h2/server/TcpServer.java
...g/h2/server/TcpServerThread.java
...n/org/h2/server/pg/PgServer.java
...org/h2/server/web/WebServer.java
...org/h2/server/web/WebThread.java
.../main/org/h2/store/FileLock.java
...ore/fs/FileObjectDiskMapped.java
.../h2/store/fs/FileSystemDisk.java
...rc/main/org/h2/table/Column.java
...ain/org/h2/table/LinkSchema.java
...main/org/h2/table/MetaTable.java
...main/org/h2/table/TableLink.java
...main/org/h2/table/TableView.java
...rc/main/org/h2/tools/Backup.java
.../tools/ChangeFileEncryption.java
...n/org/h2/tools/CompressTool.java
...c/main/org/h2/tools/Console.java
...g/h2/tools/ConvertTraceFile.java
.../org/h2/tools/CreateCluster.java
.../org/h2/tools/DeleteDbFiles.java
Project members,
sign in
to write a code review
Older revisions
r1630
by thomas.tom.mueller on Jul 15, 2009
Diff
Improved docs.
r1509
by thomas.tom.mueller on May 25, 2009
Diff
Use generics
r1502
by thomas.tom.mueller on May 22, 2009
Diff
Use generics
All revisions of this file
File info
Size: 11291 bytes, 363 lines
View raw file
File properties
svn:eol-style
native
svn:keywords
Author Date Id Revision Rev URL
Hosted by