1111import java .util .concurrent .ConcurrentLinkedQueue ;
1212import java .util .concurrent .CopyOnWriteArrayList ;
1313
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+ */
1423@ RequiredArgsConstructor
1524public final class SQLConnectionPool {
1625
@@ -19,26 +28,42 @@ public static final class Options {
1928 private int maxConnections = 10 ;
2029 }
2130
22- private final SQLConnectionBuilder from ;
31+ private final SQLConnectionBuilder builder ;
2332 private final int maxConnections ;
33+
34+ // --***-- Pooled connection caches --***--
2435 private final Queue <SQLPooledConnection > freeConnections = new ConcurrentLinkedQueue <>();
2536 private final List <SQLPooledConnection > usedConnections = new CopyOnWriteArrayList <>();
2637
2738 public SQLConnectionPool (@ NotNull SQLConnectionBuilder from ) {
2839 this (from , new Options ());
2940 }
3041
42+ /**
43+ * Creates a new connection pool.
44+ * A builder is used as a factory for creating new connections.
45+ *
46+ * @param from The builder used to create new connections.
47+ * @param poolOptions The pool options.
48+ */
3149 public SQLConnectionPool (@ NotNull SQLConnectionBuilder from , @ NotNull Options poolOptions ) {
32- this .from = from ;
50+ this .builder = from ;
3351 this .maxConnections = poolOptions .maxConnections ;
3452 }
3553
54+ /**
55+ * Gets a resource from the pool, or returns an existing one from
56+ * the pool if there is any available.
57+ *
58+ * @return The resource.
59+ * @throws SQLException Connection error.
60+ */
3661 @ NotNull
3762 public Resource getResource () throws SQLException {
3863 freeConnections .removeIf (SQLPooledConnection ::expired );
3964 SQLPooledConnection polled = freeConnections .poll ();
4065 if (polled == null && usedConnections .size () < maxConnections ) {
41- polled = new SQLPooledConnection (from .build ());
66+ polled = new SQLPooledConnection (builder .build ());
4267 polled .connection .connect ();
4368
4469 SQLException error = polled .connection .getLastError ();
@@ -50,6 +75,10 @@ public Resource getResource() throws SQLException {
5075 return new Resource (this , polled );
5176 }
5277
78+ /**
79+ * Closes all connections in the pool and
80+ * clears the caches.
81+ */
5382 public void close () {
5483 usedConnections .forEach (c -> c .connection .disconnect ());
5584 freeConnections .forEach (c -> c .connection .disconnect ());
0 commit comments