Elffuss BraidHub

kikocis/java-driver public

Avoid race between closing pool and marking it ready.
Changesetdc165191aa63661aa410a0388bdc44a145680101dcb180f2972de06f7c482758
Authorolim7t <omichallat+github@gmail.com> · 2015-05-14 16:53 +02:00
Committerolim7t <omichallat+github@gmail.com> · 2015-05-14 19:27 +02:00
Parentse464b525d39a

Browse the files at this changeset

1 file changed

modified driver-core/src/main/java/com/datastax/driver/core/HostConnectionPool.java +7 −9
@@ -72,7 +72,7 @@
7272 private final AtomicReference<CloseFuture> closeFuture = new AtomicReference<CloseFuture>();
7373
7474 private enum Phase { INITIALIZING, READY, INIT_FAILED, CLOSING }
75- private volatile Phase phase = Phase.INITIALIZING;
75+ private final AtomicReference<Phase> phase = new AtomicReference<Phase>(Phase.INITIALIZING);
7676
7777 public HostConnectionPool(final Host host, HostDistance hostDistance, final SessionManager manager){
7878 assert hostDistance != HostDistance.IGNORED;
@@ -134,14 +134,14 @@
134134 forceClose(connections);
135135 } else {
136136 logger.trace("Created connection pool to host {}", host);
137- phase = Phase.READY;
137+ phase.compareAndSet(Phase.INITIALIZING, Phase.READY);
138138 initFuture.set(null);
139139 }
140140 }
141141
142142 @Override
143143 public void onFailure(Throwable t) {
144- phase = Phase.INIT_FAILED;
144+ phase.compareAndSet(Phase.INITIALIZING, Phase.INIT_FAILED);
145145 forceClose(connections);
146146 initFuture.setException(t);
147147 }
@@ -161,9 +161,7 @@
161161 }
162162
163163 public Connection borrowConnection(long timeout, TimeUnit unit) throws ConnectionException, TimeoutException {
164- if (phase == Phase.INITIALIZING)
165- throw new ConnectionException(host.getSocketAddress(), "Pool is initializing.");
166-
164+ Phase phase = this.phase.get();
167165 if (phase != Phase.READY)
168166 // Note: throwing a ConnectionException is probably fine in practice as it will trigger the creation of a new host.
169167 // That being said, maybe having a specific exception could be cleaner.
@@ -393,7 +391,7 @@
393391 break;
394392 }
395393
396- if (phase != Phase.READY) {
394+ if (phase.get() != Phase.READY) {
397395 open.decrementAndGet();
398396 return false;
399397 }
@@ -410,7 +408,7 @@
410408 newConnection.state.compareAndSet(RESURRECTING, OPEN); // no-op if it was already OPEN
411409
412410 // We might have raced with pool shutdown since the last check; ensure the connection gets closed in case the pool did not do it.
413- if (phase != Phase.READY && !newConnection.isClosed()) {
411+ if (isClosed() && !newConnection.isClosed()) {
414412 close(newConnection);
415413 open.decrementAndGet();
416414 return false;
@@ -555,7 +553,7 @@
555553 if (future != null)
556554 return future;
557555
558- phase = Phase.CLOSING;
556+ phase.set(Phase.CLOSING);
559557
560558 // Wake up all threads that wait
561559 signalAllAvailableConnection();