1
1
2
2
package io .helidon .benchmark .nima .models ;
3
3
4
+ import java .util .concurrent .locks .ReentrantLock ;
5
+
4
6
import io .vertx .core .Vertx ;
5
7
import io .vertx .pgclient .PgConnectOptions ;
6
8
import io .vertx .pgclient .PgConnection ;
@@ -14,6 +16,7 @@ class PgClientConnectionPool implements AutoCloseable {
14
16
private final Vertx vertx ;
15
17
private final PgConnectOptions options ;
16
18
private final PgClientConnection [] connections ;
19
+ private final ReentrantLock lock = new ReentrantLock ();
17
20
18
21
public PgClientConnectionPool (Vertx vertx , int size , PgConnectOptions options ) {
19
22
this .size = size ;
@@ -24,29 +27,37 @@ public PgClientConnectionPool(Vertx vertx, int size, PgConnectOptions options) {
24
27
25
28
public PgClientConnection clientConnection () {
26
29
int bucket = Thread .currentThread ().hashCode () % size ;
30
+ if (connections [bucket ] == null ) {
31
+ try {
32
+ lock .lock ();
33
+ if (connections [bucket ] == null ) {
34
+ connect (bucket );
35
+ }
36
+ } finally {
37
+ lock .unlock ();
38
+ }
39
+ }
27
40
return connections [bucket ];
28
41
}
29
42
30
- public void connect () {
43
+ @ Override
44
+ public void close () {
31
45
try {
32
- for (int i = 0 ; i < size ; i ++) {
33
- PgConnection conn = PgConnection .connect (vertx , options )
34
- .toCompletionStage ().toCompletableFuture ().get ();
35
- PgClientConnection clientConn = new PgClientConnection (conn );
36
- clientConn .prepare ();
37
- connections [i ] = clientConn ;
46
+ for (PgClientConnection connection : connections ) {
47
+ connection .close ();
38
48
}
39
49
} catch (Exception e ) {
40
50
throw new RuntimeException (e );
41
51
}
42
52
}
43
53
44
- @ Override
45
- public void close () {
54
+ private void connect (int bucket ) {
46
55
try {
47
- for (PgClientConnection connection : connections ) {
48
- connection .close ();
49
- }
56
+ PgConnection conn = PgConnection .connect (vertx , options )
57
+ .toCompletionStage ().toCompletableFuture ().get ();
58
+ PgClientConnection clientConn = new PgClientConnection (conn );
59
+ clientConn .prepare ();
60
+ connections [bucket ] = clientConn ;
50
61
} catch (Exception e ) {
51
62
throw new RuntimeException (e );
52
63
}
0 commit comments