Elffuss BraidHub

kikocis/java-driver public

Rework connection reaper to avoid deadlock (JAVA-556).
Changeset6068c037a5f559e17764f9f60113400ca49e2ea3bdb1cee29bef6318f1d4d8f0
Authorolim7t <omichallat+github@gmail.com> · 2014-12-06 19:51 +01:00
Committerolim7t <omichallat+github@gmail.com> · 2014-12-09 18:30 +01:00
Parentsa8f731741d38

Browse the files at this changeset

3 files changed

modified driver-core/CHANGELOG.rst +1 −0
@@ -8,6 +8,7 @@
88 - [improvement] Target schema refreshes more precisely (JAVA-543)
99 - [bug] Don't check rpc_address for control host (JAVA-546)
1010 - [improvement] Improve message of NoHostAvailableException (JAVA-409)
11+- [bug] Rework connection reaper to avoid deadlock (JAVA-556)
1112
1213
1314 2.0.8:
modified driver-core/src/main/java/com/datastax/driver/core/Cluster.java +18 −16
@@ -20,6 +20,7 @@
2020 import java.net.InetSocketAddress;
2121 import java.net.UnknownHostException;
2222 import java.util.*;
23+import java.util.Map.Entry;
2324 import java.util.concurrent.*;
2425 import java.util.concurrent.atomic.AtomicInteger;
2526 import java.util.concurrent.atomic.AtomicReference;
@@ -2182,45 +2183,46 @@
21822183 * This is normally done when the connection errors out, or when the last request is processed; this class acts as
21832184 * a last-effort protection since unterminated connections can lead to deadlocks. If it terminates a connection,
21842185 * this indicates a bug; warnings are logged so that this can be reported.
2186+ *
2187+ * @see Connection#tryTerminate(boolean)
21852188 */
21862189 static class ConnectionReaper {
21872190 private static final int INTERVAL_MS = 15000;
21882191
21892192 private final ScheduledExecutorService executor = Executors.newScheduledThreadPool(1, threadFactory("Reaper-%d"));
2190- private final Set<Connection> connections = Sets.newSetFromMap(new ConcurrentHashMap<Connection, Boolean>());
2193+ private final Map<Connection, Long> connections = new ConcurrentHashMap<Connection, Long>();
21912194
21922195 private volatile boolean shutdown;
21932196
21942197 private final Runnable reaperTask = new Runnable() {
21952198 @Override
21962199 public void run() {
2197- reapConnections();
2198- if (!executor.isShutdown())
2199- executor.schedule(this, INTERVAL_MS, TimeUnit.MILLISECONDS);
2200- }
2201-
2202- private final void reapConnections() {
2203- Iterator<Connection> iterator = connections.iterator();
2200+ long now = System.currentTimeMillis();
2201+ Iterator<Entry<Connection, Long>> iterator = connections.entrySet().iterator();
22042202 while (iterator.hasNext()) {
2205- Connection connection = iterator.next();
2206- boolean terminated = connection.terminate(false, true);
2207- if (terminated)
2208- iterator.remove();
2203+ Entry<Connection, Long> entry = iterator.next();
2204+ Connection connection = entry.getKey();
2205+ Long terminateTime = entry.getValue();
2206+ if (terminateTime <= now) {
2207+ boolean terminated = connection.tryTerminate(true);
2208+ if (terminated)
2209+ iterator.remove();
2210+ }
22092211 }
22102212 }
22112213 };
22122214
22132215 ConnectionReaper() {
2214- executor.schedule(reaperTask, INTERVAL_MS, TimeUnit.MILLISECONDS);
2216+ executor.scheduleWithFixedDelay(reaperTask, INTERVAL_MS, INTERVAL_MS, TimeUnit.MILLISECONDS);
22152217 }
22162218
2217- void register(Connection connection) {
2219+ void register(Connection connection, long terminateTime) {
22182220 if (shutdown) {
22192221 // This should not happen since the reaper is shut down after all sessions.
22202222 logger.warn("Connection registered after reaper shutdown: {}", connection);
2221- connection.terminate(true, true);
2223+ connection.tryTerminate(true);
22222224 } else {
2223- connections.add(connection);
2225+ connections.put(connection, terminateTime);
22242226 }
22252227 }
22262228
modified driver-core/src/main/java/com/datastax/driver/core/Connection.java +28 −22
@@ -71,8 +71,6 @@
7171
7272 private final AtomicReference<ConnectionCloseFuture> closeFuture = new AtomicReference<ConnectionCloseFuture>();
7373
74- private final Object terminationLock = new Object();
75-
7674 /**
7775 * Create a new connection to a Cassandra node.
7876 *
@@ -409,7 +407,7 @@
409407 *
410408 * @return a future that will complete once the connection has terminated.
411409 *
412- * @see #terminate(boolean, boolean)
410+ * @see #tryTerminate(boolean)
413411 */
414412 public CloseFuture closeAsync() {
415413
@@ -421,16 +419,28 @@
421419
422420 logger.debug("{} closing connection", this);
423421
424- boolean terminated = terminate(false, false);
425- if (!terminated)
426- factory.reaper.register(this);
422+ boolean terminated = tryTerminate(false);
423+ if (!terminated) {
424+ // The time by which all pending requests should have normally completed (use twice the read timeout for a generous
425+ // estimate -- note that this does not cover the eventuality that read timeout is updated dynamically, but we can live
426+ // with that).
427+ long terminateTime = System.currentTimeMillis() + 2 * factory.getReadTimeoutMillis();
428+ factory.reaper.register(this, terminateTime);
429+ }
427430 return future;
428431 }
429432
430433 /**
431- * @return whether the connection has actually terminated
434+ * Tries to terminate a closed connection, i.e. release system resources.
435+ *
436+ * This is called both by "normal" code and by {@link Cluster.ConnectionReaper}.
437+ *
438+ * @param force whether to proceed if there are still outstanding requests.
439+ * @return whether the connection has actually terminated.
440+ *
441+ * @see #closeAsync()
432442 */
433- boolean terminate(boolean evenIfPending, boolean logWarnings) {
443+ boolean tryTerminate(boolean force) {
434444 assert isClosed();
435445 ConnectionCloseFuture future = closeFuture.get();
436446
@@ -438,18 +448,14 @@
438448 logger.debug("{} has already terminated", this);
439449 return true;
440450 } else {
441- // This method is used both by normal code and by ConnectionReaper. Since the latter is a bug detection
442- // mechanism and logs warnings when it runs, we synchronize to avoid false warnings if they race.
443- synchronized (terminationLock) {
444- if (evenIfPending || dispatcher.pending.isEmpty()) {
445- if (logWarnings)
446- logger.warn("Forcing termination of {}. This should not happen and is likely a bug, please report.", this);
447- future.force();
448- return true;
449- } else {
450- logger.debug("Not terminating {}: there are still pending requests", this);
451- return false;
452- }
451+ if (force || dispatcher.pending.isEmpty()) {
452+ if (force)
453+ logger.warn("Forcing termination of {}. This should not happen and is likely a bug, please report.", this);
454+ future.force();
455+ return true;
456+ } else {
457+ logger.debug("Not terminating {}: there are still pending requests", this);
458+ return false;
453459 }
454460 }
455461 }
@@ -609,7 +615,7 @@
609615 streamIdHandler.release(streamId);
610616
611617 if (isClosed())
612- terminate(false, false);
618+ tryTerminate(false);
613619 }
614620
615621 @Override
@@ -653,7 +659,7 @@
653659 // If we happen to be closed and we're the last outstanding request, we need to terminate the connection
654660 // (note: this is racy as the signaling can be called more than once, but that's not a problem)
655661 if (isClosed())
656- terminate(false, false);
662+ tryTerminate(false);
657663 }
658664 }
659665