Elffuss BraidHub

kikocis/java-driver public

Add periodical cleanup of closed connections.
Changesetcffdc91a122762f5affcc04f77ce415beb7fd97fbdc22ca1c3e5c8a686d933f2
Authorolim7t <omichallat+github@gmail.com> · 2014-08-25 11:51 +02:00
Committerolim7t <omichallat+github@gmail.com> · 2014-08-27 18:43 +02:00
Parents0b5c0256706f

Browse the files at this changeset

2 files changed

modified driver-core/src/main/java/com/datastax/driver/core/Cluster.java +59 −0
@@ -29,6 +29,7 @@
2929 import com.google.common.collect.Iterables;
3030 import com.google.common.collect.MapMaker;
3131 import com.google.common.collect.SetMultimap;
32+import com.google.common.collect.Sets;
3233 import com.google.common.util.concurrent.*;
3334
3435 import org.slf4j.Logger;
@@ -1091,6 +1092,8 @@
10911092 // An executor for tasks that might block some time, like creating new connection, but are generally not too critical.
10921093 final ListeningExecutorService blockingExecutor;
10931094
1095+ final ConnectionReaper reaper;
1096+
10941097 final AtomicReference<CloseFuture> closeFuture = new AtomicReference<CloseFuture>();
10951098
10961099 // All the queries that have been prepared (we keep them so we can re-prepared them when a node fail or a
@@ -1112,6 +1115,8 @@
11121115 this.executor = makeExecutor(Runtime.getRuntime().availableProcessors(), "Cassandra Java Driver worker-%d");
11131116 this.blockingExecutor = makeExecutor(2, "Cassandra Java Driver blocking tasks worker-%d");
11141117
1118+ this.reaper = new ConnectionReaper();
1119+
11151120 this.metadata = new Metadata(this);
11161121 this.contactPoints = contactPoints;
11171122 this.connectionFactory = new Connection.Factory(this, configuration);
@@ -1980,6 +1985,8 @@
19801985 // connectionFactory at the very last
19811986 connectionFactory.shutdown();
19821987
1988+ reaper.shutdown();
1989+
19831990 set(null);
19841991 } catch (InterruptedException e) {
19851992 Thread.currentThread().interrupt();
@@ -1990,4 +1997,56 @@
19901997 }
19911998 }
19921999 }
2000+
2001+ /**
2002+ * Periodically ensures that closed connections are properly terminated once they have no more pending requests.
2003+ *
2004+ * This is normally done when the connection errors out, or when the last request is processed; this class acts as
2005+ * a last-effort protection since unterminated connections can lead to deadlocks.
2006+ */
2007+ static class ConnectionReaper {
2008+ private static final int INTERVAL_MS = 5000;
2009+
2010+ private final ScheduledExecutorService executor = Executors.newScheduledThreadPool(1, threadFactory("Reaper-%d"));
2011+ private final Set<Connection> connections = Sets.newConcurrentHashSet();
2012+
2013+ private volatile boolean shutdown;
2014+
2015+ private final Runnable reaperTask = new Runnable() {
2016+ @Override
2017+ public void run() {
2018+ reapConnections();
2019+ executor.schedule(this, INTERVAL_MS, TimeUnit.MILLISECONDS);
2020+ }
2021+
2022+ private final void reapConnections() {
2023+ Iterator<Connection> iterator = connections.iterator();
2024+ while (iterator.hasNext()) {
2025+ Connection connection = iterator.next();
2026+ boolean terminated = connection.terminate(false);
2027+ if (terminated)
2028+ iterator.remove();
2029+ }
2030+ }
2031+ };
2032+
2033+ ConnectionReaper() {
2034+ executor.schedule(reaperTask, INTERVAL_MS, TimeUnit.MILLISECONDS);
2035+ }
2036+
2037+ void register(Connection connection) {
2038+ if (shutdown) {
2039+ // This should not happen since the reaper is shut down after all sessions.
2040+ logger.warn("Connection registered after reaper shutdown: {}", connection);
2041+ connection.terminate(true);
2042+ } else {
2043+ connections.add(connection);
2044+ }
2045+ }
2046+
2047+ void shutdown() {
2048+ shutdown = true;
2049+ executor.shutdown();
2050+ }
2051+ }
19932052 }
modified driver-core/src/main/java/com/datastax/driver/core/Connection.java +21 −0
@@ -407,9 +407,28 @@
407407 // the closing of the channel. However, if there no ongoing query, signal now.
408408 if (dispatcher.pending.isEmpty())
409409 future.force();
410+ else
411+ factory.reaper.register(this);
410412 return future;
411413 }
412414
415+ boolean terminate(boolean evenIfPending) {
416+ assert isClosed();
417+ ConnectionCloseFuture future = closeFuture.get();
418+
419+ if (future.isDone()) {
420+ logger.debug("{} has already terminated", this);
421+ return true;
422+ } else if (evenIfPending || dispatcher.pending.isEmpty()) {
423+ logger.warn("Forcing termination of {}. This should not happen and is likely a bug, please report.", this);
424+ future.force();
425+ return true;
426+ } else {
427+ logger.debug("Not terminating {}: there are still pending requests", this);
428+ return false;
429+ }
430+ }
431+
413432 @Override
414433 public String toString() {
415434 return String.format("Connection[%s, inFlight=%d, closed=%b]", name, inFlight.get(), isClosed());
@@ -427,6 +446,7 @@
427446 private final ConcurrentMap<Host, AtomicInteger> idGenerators = new ConcurrentHashMap<Host, AtomicInteger>();
428447 public final DefaultResponseHandler defaultHandler;
429448 final Cluster.Manager manager;
449+ final Cluster.ConnectionReaper reaper;
430450 public final Configuration configuration;
431451
432452 public final AuthProvider authProvider;
@@ -437,6 +457,7 @@
437457 Factory(Cluster.Manager manager, Configuration configuration) {
438458 this.defaultHandler = manager;
439459 this.manager = manager;
460+ this.reaper = manager.reaper;
440461 this.configuration = configuration;
441462 this.authProvider = configuration.getProtocolOptions().getAuthProvider();
442463 this.protocolVersion = configuration.getProtocolOptions().initialProtocolVersion;