blob: af79b521422189e570a50e284966b19ccd92116c (
plain) (
blame)
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
|
package sql;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Collections;
import java.util.Queue;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentLinkedQueue;
import models.Configuration;
import org.apache.log4j.Logger;
public class SQL {
private static final Logger LOGGER = Logger.getLogger(SQL.class);
/**
* Pool of available connections.
*/
private static final Queue<MysqlConnection> pool = new ConcurrentLinkedQueue<>();
/**
* Set of connections currently handed out.
*/
private static final Set<MysqlConnection> busyConnections = Collections.newSetFromMap(new ConcurrentHashMap<MysqlConnection, Boolean>());
static {
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
} catch (InstantiationException | IllegalAccessException | ClassNotFoundException e) {
LOGGER.fatal("Cannot get mysql JDBC driver!", e);
System.exit(1);
}
}
public static MysqlConnection getConnection() {
MysqlConnection con;
for (;;) {
con = pool.poll();
if (con == null)
break;
if (!con.isValid()) {
con.release();
continue;
}
if (!busyConnections.add(con))
throw new RuntimeException("Tried to hand out a busy connection!");
return con;
}
// No pooled connection
if (busyConnections.size() > 20) {
LOGGER.warn("Too many open MySQL connections. Possible connection leak!");
return null;
}
try {
// Create fresh connection
Connection rawConnection = DriverManager.getConnection(Configuration.getDbUri(),
Configuration.getDbUsername(), Configuration.getDbPassword());
// By convention in our program we don't want auto commit
rawConnection.setAutoCommit(false);
// Wrap into our proxy
con = new MysqlConnection(rawConnection);
// Keep track of busy mysql connection
if (!busyConnections.add(con))
throw new RuntimeException("Tried to hand out a busy connection!");
return con;
} catch (SQLException e) {
LOGGER.info("Failed to connect to local mysql server", e);
}
return null;
}
static void returnConnection(MysqlConnection connection) {
if (!busyConnections.remove(connection))
throw new RuntimeException("Tried to return a mysql connection to the pool that was not taken!");
pool.add(connection);
}
}// end class
|