Skip to content

Commit 1f8ad70

Browse files
committed
New locking strategy.
Signed-off-by: Santiago Pericas-Geertsen <[email protected]>
1 parent d5f67f5 commit 1f8ad70

File tree

1 file changed

+17
-13
lines changed

1 file changed

+17
-13
lines changed

frameworks/Java/helidon/nima/src/main/java/io/helidon/benchmark/nima/models/PgClientConnectionPoolArray.java

Lines changed: 17 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,8 @@
11

22
package io.helidon.benchmark.nima.models;
33

4-
import java.util.concurrent.locks.ReentrantLock;
4+
import java.util.concurrent.locks.ReadWriteLock;
5+
import java.util.concurrent.locks.ReentrantReadWriteLock;
56
import java.util.logging.Logger;
67

78
import io.helidon.config.Config;
@@ -13,7 +14,7 @@ class PgClientConnectionPoolArray extends PgClientConnectionPool {
1314

1415
private final int connections;
1516
private final PgClientConnection[] connectionArray;
16-
private final ReentrantLock lock = new ReentrantLock();
17+
private final ReadWriteLock lock = new ReentrantReadWriteLock();
1718

1819
PgClientConnectionPoolArray(Vertx vertx, PgConnectOptions options, Config config) {
1920
super(vertx, options, config);
@@ -29,20 +30,23 @@ class PgClientConnectionPoolArray extends PgClientConnectionPool {
2930
@Override
3031
public PgClientConnection clientConnection() {
3132
int index = Thread.currentThread().hashCode() % connections;
32-
PgClientConnection connection = connectionArray[index];
33-
if (connection == null) {
34-
try {
35-
lock.lock();
36-
connection = connectionArray[index];
37-
if (connection == null) {
38-
connection = newConnection();
39-
connectionArray[index] = connection;
33+
if (connectionArray[index] == null) {
34+
lock.readLock().lock();
35+
if (connectionArray[index] == null) {
36+
lock.readLock().unlock();
37+
lock.writeLock().lock();
38+
try {
39+
if (connectionArray[index] == null) {
40+
connectionArray[index] = newConnection();
41+
}
42+
} finally {
43+
lock.writeLock().unlock();
4044
}
41-
} finally {
42-
lock.unlock();
45+
} else {
46+
lock.readLock().unlock();
4347
}
4448
}
45-
return connection;
49+
return connectionArray[index];
4650
}
4751

4852
@Override

0 commit comments

Comments
 (0)