Elffuss BraidHub

kikocis/java-driver public

Avoid possible NPE in HostConnectionPool

JAVA-231 #fixes
Changesetd9d1c2a96166f90b9c55c13f7825c185e5ba91c7c2e80088b176a40baef1c685
AuthorSylvain Lebresne <sylvain@datastax.com> · 2014-01-03 14:08 +01:00
CommitterSylvain Lebresne <sylvain@datastax.com> · 2014-01-03 14:08 +01:00
Parents9c79c9f1b873

Browse the files at this changeset

1 file changed

modified driver-core/src/main/java/com/datastax/driver/core/HostConnectionPool.java +29 −15
@@ -126,16 +126,26 @@
126126 if (minInFlight >= options().getMaxSimultaneousRequestsPerConnectionThreshold(hostDistance) && connections.size() < options().getMaxConnectionsPerHost(hostDistance))
127127 maybeSpawnNewConnection();
128128
129- while (true) {
130- int inFlight = leastBusy.inFlight.get();
131-
132- if (inFlight >= leastBusy.maxAvailableStreams()) {
133- leastBusy = waitForConnection(timeout, unit);
134- break;
135- }
129+ if (leastBusy == null) {
130+ // We could have raced with a shutdown since the last check
131+ if (isShutdown.get())
132+ throw new ConnectionException(host.getAddress(), "Pool is shutdown");
133+ // This might maybe happen if the number of core connections per host is 0 and a connection was trashed between
134+ // the previous check to connections and now. But in that case, the line above will have trigger the creation of
135+ // a new connection, so just wait that connection and move on
136+ leastBusy = waitForConnection(timeout, unit);
137+ } else {
138+ while (true) {
139+ int inFlight = leastBusy.inFlight.get();
140+
141+ if (inFlight >= leastBusy.maxAvailableStreams()) {
142+ leastBusy = waitForConnection(timeout, unit);
143+ break;
144+ }
136145
137- if (leastBusy.inFlight.compareAndSet(inFlight, inFlight + 1))
138- break;
146+ if (leastBusy.inFlight.compareAndSet(inFlight, inFlight + 1))
147+ break;
148+ }
139149 }
140150 leastBusy.setKeyspace(manager.poolsState.keyspace);
141151 return leastBusy;
@@ -203,14 +213,18 @@
203213 }
204214 }
205215
206- while (true) {
207- int inFlight = leastBusy.inFlight.get();
216+ // If we race with shutdown, leastBusy could be null. In that case we just loop and we'll throw on the next
217+ // iteration anyway
218+ if (leastBusy != null) {
219+ while (true) {
220+ int inFlight = leastBusy.inFlight.get();
208221
209- if (inFlight >= leastBusy.maxAvailableStreams())
210- break;
222+ if (inFlight >= leastBusy.maxAvailableStreams())
223+ break;
211224
212- if (leastBusy.inFlight.compareAndSet(inFlight, inFlight + 1))
213- return leastBusy;
225+ if (leastBusy.inFlight.compareAndSet(inFlight, inFlight + 1))
226+ return leastBusy;
227+ }
214228 }
215229
216230 remaining = timeout - Cluster.timeSince(start, unit);