Elffuss BraidHub

kikocis/java-driver public

Fix memory leak caused by Connection#flusherLookup.

Discovered while running ClusterStressTest that there was a lot of
heap pressure as more Cluster instances were created.  Upon further
investigation found that Connection#flusherLookup was the culprit as it
is not cleaned up as Clusters are closed.  To solve this, made
flusherLookup a concurrent map with weak keys and made Flusher#eventLoop
a weak reference.  This way as the EventLoopGroups become closed their
associated EventLoops will be marked as weak references and eventually
cleaned up by the garbage collector.
Changeset5095909642853f9525e940cd938fde82db613d237a29b4ee510fd95575293ac3
AuthorAndrew Tolbert <andrew.tolbert@datastax.com> · 2015-04-10 00:00 -05:00
Committerolim7t <omichallat+github@gmail.com> · 2015-04-17 20:19 +02:00
Parents0e7ff2256dc1

Browse the files at this changeset

1 file changed

modified driver-core/src/main/java/com/datastax/driver/core/Connection.java +15 −5
@@ -15,6 +15,7 @@
1515 */
1616 package com.datastax.driver.core;
1717
18+import java.lang.ref.WeakReference;
1819 import java.net.InetSocketAddress;
1920 import java.util.HashSet;
2021 import java.util.Iterator;
@@ -26,6 +27,7 @@
2627 import java.util.concurrent.atomic.AtomicReference;
2728
2829 import com.google.common.collect.Lists;
30+import com.google.common.collect.MapMaker;
2931 import com.google.common.util.concurrent.*;
3032 import io.netty.bootstrap.Bootstrap;
3133 import io.netty.channel.*;
@@ -780,7 +782,7 @@
780782 }
781783
782784 private static final class Flusher implements Runnable {
783- final EventLoop eventLoop;
785+ final WeakReference<EventLoop> eventLoopRef;
784786 final Queue<FlushItem> queued = new ConcurrentLinkedQueue<FlushItem>();
785787 final AtomicBoolean running = new AtomicBoolean(false);
786788 final HashSet<Channel> channels = new HashSet<Channel>();
@@ -789,12 +791,14 @@
789791 int runsWithNoWork = 0;
790792
791793 private Flusher(EventLoop eventLoop) {
792- this.eventLoop = eventLoop;
794+ this.eventLoopRef = new WeakReference<EventLoop>(eventLoop);
793795 }
794796
795797 void start() {
796798 if (!running.get() && running.compareAndSet(false, true)) {
797- this.eventLoop.execute(this);
799+ EventLoop eventLoop = eventLoopRef.get();
800+ if (eventLoop != null)
801+ eventLoop.execute(this);
798802 }
799803 }
800804
@@ -832,11 +836,17 @@
832836 }
833837 }
834838
835- eventLoop.schedule(this, 10000, TimeUnit.NANOSECONDS);
839+ EventLoop eventLoop = eventLoopRef.get();
840+ if(eventLoop != null) {
841+ eventLoop.schedule(this, 10000, TimeUnit.NANOSECONDS);
842+ }
836843 }
837844 }
838845
839- private static final ConcurrentMap<EventLoop, Flusher> flusherLookup = new ConcurrentHashMap<EventLoop, Flusher>();
846+ private static final ConcurrentMap<EventLoop, Flusher> flusherLookup = new MapMaker()
847+ .concurrencyLevel(16)
848+ .weakKeys()
849+ .makeMap();
840850
841851 private static class FlushItem {
842852 final Channel channel;