|
1 | 1 | package me.zort.sqllib; |
2 | 2 |
|
3 | | -import java.sql.Connection; |
| 3 | +import lombok.AccessLevel; |
| 4 | +import lombok.Data; |
| 5 | +import lombok.RequiredArgsConstructor; |
| 6 | +import org.jetbrains.annotations.NotNull; |
| 7 | + |
| 8 | +import java.sql.SQLException; |
4 | 9 | import java.util.List; |
5 | | -import java.util.Optional; |
| 10 | +import java.util.Queue; |
| 11 | +import java.util.concurrent.ConcurrentLinkedQueue; |
6 | 12 | import java.util.concurrent.CopyOnWriteArrayList; |
7 | 13 |
|
| 14 | +/** |
| 15 | + * A connection pool. |
| 16 | + * <p></p> |
| 17 | + * This class is used to create a pool of connections to a database. |
| 18 | + * It is recommended to use this class instead of creating a new connection |
| 19 | + * every time you need to execute a query. |
| 20 | + * |
| 21 | + * @author ZorTik |
| 22 | + */ |
| 23 | +@RequiredArgsConstructor |
8 | 24 | public final class SQLConnectionPool { |
9 | 25 |
|
10 | | - private SQLConnectionPool() { |
| 26 | + @Data |
| 27 | + public static final class Options { |
| 28 | + // Max number of connections in the pool |
| 29 | + private int maxConnections = 10; |
| 30 | + // Max wait time for getResource in milliseconds when the pool is exhausted |
| 31 | + private long borrowObjectTimeout = 5000L; |
| 32 | + // Block or throw an exception when the pool is exhausted |
| 33 | + private boolean blockWhenExhausted = true; |
| 34 | + } |
| 35 | + |
| 36 | + private final SQLConnectionBuilder builder; |
| 37 | + private final int maxConnections; |
| 38 | + private final long borrowObjectTimeout; |
| 39 | + private final boolean blockWhenExhausted; |
| 40 | + |
| 41 | + // --***-- Pooled connection caches --***-- |
| 42 | + private final Queue<SQLPooledConnection> freeConnections = new ConcurrentLinkedQueue<>(); |
| 43 | + private final List<SQLPooledConnection> usedConnections = new CopyOnWriteArrayList<>(); |
| 44 | + |
| 45 | + public SQLConnectionPool(@NotNull SQLConnectionBuilder from) { |
| 46 | + this(from, new Options()); |
| 47 | + } |
| 48 | + |
| 49 | + /** |
| 50 | + * Creates a new connection pool. |
| 51 | + * A builder is used as a factory for creating new connections. |
| 52 | + * |
| 53 | + * @param from The builder used to create new connections. |
| 54 | + * @param poolOptions The pool options. |
| 55 | + */ |
| 56 | + public SQLConnectionPool(@NotNull SQLConnectionBuilder from, @NotNull Options poolOptions) { |
| 57 | + this.builder = from; |
| 58 | + this.maxConnections = poolOptions.maxConnections; |
| 59 | + this.borrowObjectTimeout = poolOptions.borrowObjectTimeout; |
| 60 | + this.blockWhenExhausted = poolOptions.blockWhenExhausted; |
11 | 61 | } |
12 | 62 |
|
13 | | - private static final List<SQLDatabaseConnection> CONNECTIONS = new CopyOnWriteArrayList<>(); |
| 63 | + /** |
| 64 | + * Gets a resource from the pool, or returns an existing one from |
| 65 | + * the pool if there is any available. |
| 66 | + * |
| 67 | + * @return The resource. |
| 68 | + * @throws SQLException Connection error. |
| 69 | + */ |
| 70 | + @NotNull |
| 71 | + public Resource getResource() throws SQLException { |
| 72 | + freeConnections.removeIf(SQLPooledConnection::expired); |
| 73 | + SQLPooledConnection polled = freeConnections.poll(); |
| 74 | + if (polled == null && size() < maxConnections) { |
| 75 | + polled = establishObject(); |
| 76 | + } else if(polled == null) { |
| 77 | + |
| 78 | + if (!blockWhenExhausted) { |
| 79 | + throw new SQLException("No connections available."); |
| 80 | + } |
14 | 81 |
|
15 | | - static void register(SQLDatabaseConnection connection) { |
16 | | - CONNECTIONS.add(connection); |
| 82 | + long start = System.currentTimeMillis(); |
| 83 | + while ((polled = freeConnections.poll()) == null) { |
| 84 | + if (System.currentTimeMillis() - start > borrowObjectTimeout) { |
| 85 | + throw new SQLException("Timeout while waiting for a connection."); |
| 86 | + } else if(size() < maxConnections) { |
| 87 | + polled = establishObject(); |
| 88 | + break; |
| 89 | + } |
| 90 | + } |
| 91 | + } |
| 92 | + usedConnections.add(polled); |
| 93 | + return new Resource(this, polled); |
17 | 94 | } |
18 | 95 |
|
19 | | - static Optional<SQLDatabaseConnection> find(Connection connection) { |
20 | | - return CONNECTIONS.stream().filter(c -> c.getConnection() == connection).findFirst(); |
| 96 | + private SQLPooledConnection establishObject() throws SQLException { |
| 97 | + SQLPooledConnection polled = new SQLPooledConnection(builder.build()); |
| 98 | + polled.connection.connect(); |
| 99 | + |
| 100 | + SQLException error = polled.connection.getLastError(); |
| 101 | + if (error != null) throw error; |
| 102 | + |
| 103 | + if (polled.connection instanceof SQLDatabaseConnectionImpl) { |
| 104 | + ((SQLDatabaseConnectionImpl) polled.connection).addErrorHandler(code -> { |
| 105 | + // Remove the connection from the pool and disconnect |
| 106 | + // on fatal errors. |
| 107 | + freeConnections.remove(polled); |
| 108 | + usedConnections.remove(polled); |
| 109 | + polled.connection.disconnect(); |
| 110 | + }); |
| 111 | + } |
| 112 | + |
| 113 | + return polled; |
| 114 | + } |
| 115 | + |
| 116 | + public int size() { |
| 117 | + return usedConnections.size() + freeConnections.size(); |
| 118 | + } |
| 119 | + |
| 120 | + /** |
| 121 | + * Closes all connections in the pool and |
| 122 | + * clears the caches. |
| 123 | + */ |
| 124 | + public void close() { |
| 125 | + usedConnections.forEach(c -> c.connection.disconnect()); |
| 126 | + freeConnections.forEach(c -> c.connection.disconnect()); |
| 127 | + usedConnections.clear(); |
| 128 | + freeConnections.clear(); |
| 129 | + } |
| 130 | + |
| 131 | + @RequiredArgsConstructor(access = AccessLevel.PRIVATE) |
| 132 | + private static final class SQLPooledConnection { |
| 133 | + private final SQLDatabaseConnection connection; |
| 134 | + private long lastUsed = System.currentTimeMillis(); |
| 135 | + |
| 136 | + public boolean expired() { |
| 137 | + return System.currentTimeMillis() - lastUsed > 1000 * 60 * 5; |
| 138 | + } |
| 139 | + } |
| 140 | + |
| 141 | + @RequiredArgsConstructor(access = AccessLevel.PRIVATE) |
| 142 | + public static final class Resource implements AutoCloseable { |
| 143 | + |
| 144 | + private final SQLConnectionPool pool; |
| 145 | + private final SQLPooledConnection connection; |
| 146 | + |
| 147 | + public SQLDatabaseConnection getConnection() { |
| 148 | + return connection.connection; |
| 149 | + } |
| 150 | + |
| 151 | + @Override |
| 152 | + public void close() { |
| 153 | + connection.lastUsed = System.currentTimeMillis(); |
| 154 | + pool.freeConnections.add(connection); |
| 155 | + pool.usedConnections.remove(connection); |
| 156 | + } |
21 | 157 | } |
22 | 158 |
|
23 | 159 | } |
0 commit comments