Skip to content

Commit b767c72

Browse files
committed
Fixed data race on creation of cached contexts
1 parent cdd907d commit b767c72

File tree

2 files changed

+29
-2
lines changed

2 files changed

+29
-2
lines changed

jdbc/src/main/java/tech/ydb/jdbc/YdbDriver.java

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -77,9 +77,10 @@ public YdbContext getCachedContext(YdbConfig config) throws SQLException {
7777
}
7878

7979
context = YdbContext.createContext(config);
80-
YdbContext old = cache.put(config, context);
80+
YdbContext old = cache.putIfAbsent(config, context);
8181
if (old != null) {
82-
old.close();
82+
context.close();
83+
return old;
8384
}
8485
return context;
8586
}

jdbc/src/test/java/tech/ydb/jdbc/YdbDriverIntegrationTest.java

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,8 +4,11 @@
44
import java.sql.DriverManager;
55
import java.sql.SQLException;
66
import java.util.ArrayDeque;
7+
import java.util.ArrayList;
78
import java.util.Deque;
9+
import java.util.List;
810
import java.util.Properties;
11+
import java.util.concurrent.CompletableFuture;
912

1013
import org.junit.jupiter.api.Assertions;
1114
import org.junit.jupiter.api.Test;
@@ -98,6 +101,29 @@ public void testContextCache() throws SQLException {
98101
}
99102
}
100103

104+
@Test
105+
public void testContextCacheConncurrent() throws SQLException {
106+
List<CompletableFuture<YdbContext>> list = new ArrayList<>();
107+
108+
for (int idx = 0; idx < 20; idx++) {
109+
list.add(CompletableFuture.supplyAsync(() -> {
110+
try (Connection conn1 = DriverManager.getConnection(jdbcURL.build())) {
111+
YdbConnection unwrapped = conn1.unwrap(YdbConnection.class);
112+
Assertions.assertNotNull(unwrapped.getCtx());
113+
return unwrapped.getCtx();
114+
} catch (SQLException ex) {
115+
throw new RuntimeException("Cannot connect", ex);
116+
}
117+
}));
118+
}
119+
120+
YdbContext first = list.get(0).join();
121+
122+
for (CompletableFuture<YdbContext> future: list) {
123+
Assertions.assertEquals(first, future.join());
124+
}
125+
}
126+
101127
@Test
102128
public void testResizeSessionPool() throws SQLException {
103129
String url = jdbcURL.build();

0 commit comments

Comments
 (0)