Elffuss BraidHub

kikocis/java-driver public

Allow Cluster subclasses to delegate to another instance (JAVA-619).

This moves all significant work to Cluster.Manager.init(). A delegating
subclass must ensure that init() is never called in the parent class, so
that extra ressources like thread pools are not created unnecessarily.

This is a workaround for the fact that Cluster should be an interface,
which would be a better way to address this use case, but can't be done
for compatibility reasons.
Changesetf68609ba757ee5d131e27dc712c6bb3708cf46a37ee25f53f8f0ec6694e15cce
Authorolim7t <omichallat+github@gmail.com> · 2015-04-01 12:21 +02:00
Committerolim7t <omichallat+github@gmail.com> · 2015-04-03 12:43 +02:00
Parents4f26e3f5cefb

Browse the files at this changeset

4 files changed

modified driver-core/CHANGELOG.rst +2 −0
@@ -34,6 +34,8 @@
3434 - [bug] Fix issue when executing a PreparedStatement from another cluster
3535 (JAVA-641)
3636 - [improvement] Log keyspace xxx does not exist at WARN level (JAVA-534)
37+- [improvement] Allow Cluster subclasses to delegate to another instance
38+ (JAVA-619)
3739
3840 Merged from 2.0.9_fixes branch:
3941
modified driver-core/src/main/java/com/datastax/driver/core/Cluster.java +79 −61
@@ -218,6 +218,7 @@
218218 * @return a new, non-initialized session on this cluster.
219219 */
220220 public Session newSession() {
221+ checkNotClosed(manager);
221222 return manager.newSession();
222223 }
223224
@@ -242,6 +243,7 @@
242243 * Cluster.
243244 */
244245 public Session connect() {
246+ checkNotClosed(manager);
245247 init();
246248 Session session = manager.newSession();
247249 session.init();
@@ -351,6 +353,7 @@
351353 * returns {@code null}).
352354 */
353355 public Metrics getMetrics() {
356+ checkNotClosed(manager);
354357 return manager.metrics;
355358 }
356359
@@ -369,6 +372,7 @@
369372 * @return this {@code Cluster} object;
370373 */
371374 public Cluster register(Host.StateListener listener) {
375+ checkNotClosed(manager);
372376 manager.listeners.add(listener);
373377 return this;
374378 }
@@ -383,6 +387,7 @@
383387 * @return this {@code Cluster} object;
384388 */
385389 public Cluster unregister(Host.StateListener listener) {
390+ checkNotClosed(manager);
386391 manager.listeners.remove(listener);
387392 return this;
388393 }
@@ -407,6 +412,7 @@
407412 * @return this {@code Cluster} object;
408413 */
409414 public Cluster register(LatencyTracker tracker) {
415+ checkNotClosed(manager);
410416 manager.trackers.add(tracker);
411417 return this;
412418 }
@@ -422,6 +428,7 @@
422428 * @return this {@code Cluster} object;
423429 */
424430 public Cluster unregister(LatencyTracker tracker) {
431+ checkNotClosed(manager);
425432 manager.trackers.remove(tracker);
426433 return this;
427434 }
@@ -480,6 +487,11 @@
480487 return manager.closeFuture.get() != null;
481488 }
482489
490+ private static void checkNotClosed(Manager manager) {
491+ if (manager.isClosed())
492+ throw new IllegalStateException("Can't use this cluster instance because it was previously closed");
493+ }
494+
483495 /**
484496 * Initializer for {@link Cluster} instances.
485497 * <p>
@@ -1094,33 +1106,31 @@
10941106 final List<InetSocketAddress> contactPoints;
10951107 final Set<SessionManager> sessions = new CopyOnWriteArraySet<SessionManager>();
10961108
1097- final Metadata metadata;
1109+ Metadata metadata;
10981110 final Configuration configuration;
1099- final Metrics metrics;
1111+ Metrics metrics;
11001112
1101- final Connection.Factory connectionFactory;
1102- final ControlConnection controlConnection;
1113+ Connection.Factory connectionFactory;
1114+ ControlConnection controlConnection;
11031115
11041116 final ConvictionPolicy.Factory convictionPolicyFactory = new ConvictionPolicy.Simple.Factory();
11051117
1106- final ScheduledThreadPoolExecutor reconnectionExecutor;
1107- // scheduledTasksExecutor is used to process C* notifications. So having it mono-threaded ensures notifications are
1108- // applied in the order received.
1109- final ScheduledThreadPoolExecutor scheduledTasksExecutor;
1118+ ScheduledThreadPoolExecutor reconnectionExecutor;
1119+ ScheduledThreadPoolExecutor scheduledTasksExecutor;
11101120
11111121 // Executor used for tasks that shouldn't be executed on an IO thread. Used for short-lived, generally non-blocking tasks
1112- final ListeningExecutorService executor;
1122+ ListeningExecutorService executor;
11131123
11141124 // Work Queue used by executor.
1115- final LinkedBlockingQueue<Runnable> executorQueue = new LinkedBlockingQueue<Runnable>();
1125+ LinkedBlockingQueue<Runnable> executorQueue;
11161126
11171127 // An executor for tasks that might block some time, like creating new connection, but are generally not too critical.
1118- final ListeningExecutorService blockingExecutor;
1128+ ListeningExecutorService blockingExecutor;
11191129
11201130 // Work Queue used by blockingExecutor.
1121- final LinkedBlockingQueue<Runnable> blockingExecutorQueue = new LinkedBlockingQueue<Runnable>();
1131+ LinkedBlockingQueue<Runnable> blockingExecutorQueue;
11221132
1123- final ConnectionReaper reaper;
1133+ ConnectionReaper reaper;
11241134
11251135 final AtomicReference<CloseFuture> closeFuture = new AtomicReference<CloseFuture>();
11261136
@@ -1128,44 +1138,48 @@
11281138 // new one join the cluster).
11291139 // Note: we could move this down to the session level, but since prepared statement are global to a node,
11301140 // this would yield a slightly less clear behavior.
1131- final ConcurrentMap<MD5Digest, PreparedStatement> preparedQueries = new MapMaker().weakValues().makeMap();
1141+ ConcurrentMap<MD5Digest, PreparedStatement> preparedQueries;
11321142
11331143 final Set<Host.StateListener> listeners;
11341144 final Set<LatencyTracker> trackers = new CopyOnWriteArraySet<LatencyTracker>();
11351145
11361146 private Manager(String clusterName, List<InetSocketAddress> contactPoints, Configuration configuration, Collection<Host.StateListener> listeners) {
1137- logger.debug("Starting new cluster with contact points " + contactPoints);
1138-
11391147 this.clusterName = clusterName == null ? generateClusterName() : clusterName;
11401148 this.configuration = configuration;
1149+ this.contactPoints = contactPoints;
1150+ this.listeners = new CopyOnWriteArraySet<Host.StateListener>(listeners);
1151+ }
1152+
1153+ // Initialization is not too performance intensive and in practice there shouldn't be contention
1154+ // on it so synchronized is good enough.
1155+ synchronized void init() {
1156+ checkNotClosed(this);
1157+ if (isInit)
1158+ return;
1159+ isInit = true;
1160+
1161+ logger.debug("Starting new cluster with contact points " + contactPoints);
1162+
11411163 this.configuration.register(this);
11421164
1165+ this.executorQueue = new LinkedBlockingQueue<Runnable>();
11431166 this.executor = makeExecutor(NON_BLOCKING_EXECUTOR_SIZE, "worker", executorQueue);
1167+ this.blockingExecutorQueue = new LinkedBlockingQueue<Runnable>();
11441168 this.blockingExecutor = makeExecutor(2, "blocking-task-worker", blockingExecutorQueue);
11451169 this.reconnectionExecutor = new ScheduledThreadPoolExecutor(2, threadFactory("reconnection"));
1170+ // scheduledTasksExecutor is used to process C* notifications. So having it mono-threaded ensures notifications are
1171+ // applied in the order received.
11461172 this.scheduledTasksExecutor = new ScheduledThreadPoolExecutor(1, threadFactory("scheduled-task-worker"));
11471173
11481174 this.reaper = new ConnectionReaper(this);
1149-
11501175 this.metadata = new Metadata(this);
1151- this.contactPoints = contactPoints;
11521176 this.connectionFactory = new Connection.Factory(this, configuration);
11531177 this.controlConnection = new ControlConnection(this);
1154-
11551178 this.metrics = configuration.getMetricsOptions() == null ? null : new Metrics(this);
1156- this.listeners = new CopyOnWriteArraySet<Host.StateListener>(listeners);
1179+ this.preparedQueries = new MapMaker().weakValues().makeMap();
11571180
11581181 this.scheduledTasksExecutor.scheduleWithFixedDelay(new CleanupIdleConnectionsTask(), 10, 10, TimeUnit.SECONDS);
1159- }
11601182
1161- // Initialization is not too performance intensive and in practice there shouldn't be contention
1162- // on it so synchronized is good enough.
1163- synchronized void init() {
1164- if (isClosed())
1165- throw new IllegalStateException("Can't use this Cluster instance because it was previously closed");
1166- if (isInit)
1167- return;
1168- isInit = true;
11691183
11701184 for (InetSocketAddress address : contactPoints) {
11711185 // We don't want to signal -- call onAdd() -- because nothing is ready
@@ -1306,39 +1320,43 @@
13061320 if (future != null)
13071321 return future;
13081322
1309- logger.debug("Shutting down");
1310-
1311- // If we're shutting down, there is no point in waiting on scheduled reconnections, nor on notifications
1312- // delivery or blocking tasks so we use shutdownNow
1313- shutdownNow(reconnectionExecutor);
1314- shutdownNow(scheduledTasksExecutor);
1315- shutdownNow(blockingExecutor);
1316-
1317- // but for the worker executor, we want to let submitted tasks finish unless the shutdown is forced.
1318- executor.shutdown();
1319-
1320- // We also close the metrics
1321- if (metrics != null)
1322- metrics.shutdown();
1323-
1324- // And the load balancing policy
1325- LoadBalancingPolicy loadBalancingPolicy = loadBalancingPolicy();
1326- if (loadBalancingPolicy instanceof CloseableLoadBalancingPolicy)
1327- ((CloseableLoadBalancingPolicy)loadBalancingPolicy).close();
1328-
1329- AddressTranslater translater = configuration.getPolicies().getAddressTranslater();
1330- if (translater instanceof CloseableAddressTranslater)
1331- ((CloseableAddressTranslater)translater).close();
1332-
1333- // Then we shutdown all connections
1334- List<CloseFuture> futures = new ArrayList<CloseFuture>(sessions.size() + 1);
1335- futures.add(controlConnection.closeAsync());
1336- for (Session session : sessions)
1337- futures.add(session.closeAsync());
1338-
1339- future = new ClusterCloseFuture(futures);
1323+ if (isInit) {
1324+ logger.debug("Shutting down");
1325+
1326+ // If we're shutting down, there is no point in waiting on scheduled reconnections, nor on notifications
1327+ // delivery or blocking tasks so we use shutdownNow
1328+ shutdownNow(reconnectionExecutor);
1329+ shutdownNow(scheduledTasksExecutor);
1330+ shutdownNow(blockingExecutor);
1331+
1332+ // but for the worker executor, we want to let submitted tasks finish unless the shutdown is forced.
1333+ executor.shutdown();
1334+
1335+ // We also close the metrics
1336+ if (metrics != null)
1337+ metrics.shutdown();
1338+
1339+ // And the load balancing policy
1340+ LoadBalancingPolicy loadBalancingPolicy = loadBalancingPolicy();
1341+ if (loadBalancingPolicy instanceof CloseableLoadBalancingPolicy)
1342+ ((CloseableLoadBalancingPolicy)loadBalancingPolicy).close();
1343+
1344+ AddressTranslater translater = configuration.getPolicies().getAddressTranslater();
1345+ if (translater instanceof CloseableAddressTranslater)
1346+ ((CloseableAddressTranslater)translater).close();
1347+
1348+ // Then we shutdown all connections
1349+ List<CloseFuture> futures = new ArrayList<CloseFuture>(sessions.size() + 1);
1350+ futures.add(controlConnection.closeAsync());
1351+ for (Session session : sessions)
1352+ futures.add(session.closeAsync());
1353+
1354+ future = new ClusterCloseFuture(futures);
1355+ // The rest will happen asynchronously, when all connections are successfully closed
1356+ } else {
1357+ future = CloseFuture.immediateFuture();
1358+ }
13401359
1341- // The rest will happen asynchronously, when all connections are successfully closed
13421360 return closeFuture.compareAndSet(null, future)
13431361 ? future
13441362 : closeFuture.get(); // We raced, it's ok, return the future that was actually set
added driver-core/src/main/java/com/datastax/driver/core/DelegatingCluster.java +111 −0
@@ -0,0 +1,111 @@
1+package com.datastax.driver.core;
2+
3+import java.net.InetSocketAddress;
4+import java.util.Collections;
5+
6+/**
7+ * Base class for custom {@link Cluster} implementations that wrap another instance (delegate / decorator pattern).
8+ */
9+public abstract class DelegatingCluster extends Cluster {
10+ /**
11+ * Builds a new instance.
12+ */
13+ protected DelegatingCluster() {
14+ // Implementation notes:
15+ // If Cluster was an interface, delegates would be trivial to write. But, for historical reasons, it's a class,
16+ // and changing that would break backward compatibility. That makes delegates rather convoluted and error-prone
17+ // to write, so we provide DelegatingCluster to abstract the details.
18+ // This class ensures that:
19+ // - init() is never called on the parent class, because that would initialize the Cluster.Manager instance and
20+ // create a lot of internal state (thread pools, etc.) that we don't need, since another Cluster instance is
21+ // already handling the calls.
22+ // - all public methods are properly forwarded to the delegate (otherwise they would call the parent class and
23+ // return inconsistent results).
24+ // These two goals are closely related, since a lot of public methods call init(), so accidentally calling a
25+ // parent method could initialize the parent state.
26+
27+ // Construct parent class with dummy parameters that will never get used (since super.init() is never called).
28+ super("delegating_cluster", Collections.<InetSocketAddress>emptyList(), null);
29+
30+ // Immediately close the parent class's internal Manager, to make sure that it will fail fast if it's ever
31+ // accidentally invoked.
32+ super.closeAsync();
33+ }
34+
35+ /**
36+ * Returns the delegate instance where all calls will be forwarded.
37+ *
38+ * @return the delegate.
39+ */
40+ protected abstract Cluster delegate();
41+
42+ @Override
43+ public Cluster init() {
44+ return delegate().init();
45+ }
46+
47+ @Override
48+ public Session newSession() {
49+ return delegate().newSession();
50+ }
51+
52+ @Override
53+ public Session connect() {
54+ return delegate().connect();
55+ }
56+
57+ @Override
58+ public Session connect(String keyspace) {
59+ return delegate().connect(keyspace);
60+ }
61+
62+ @Override
63+ public Metadata getMetadata() {
64+ return delegate().getMetadata();
65+ }
66+
67+ @Override
68+ public Configuration getConfiguration() {
69+ return delegate().getConfiguration();
70+ }
71+
72+ @Override
73+ public Metrics getMetrics() {
74+ return delegate().getMetrics();
75+ }
76+
77+ @Override
78+ public Cluster register(Host.StateListener listener) {
79+ return delegate().register(listener);
80+ }
81+
82+ @Override
83+ public Cluster unregister(Host.StateListener listener) {
84+ return delegate().unregister(listener);
85+ }
86+
87+ @Override
88+ public Cluster register(LatencyTracker tracker) {
89+ return delegate().register(tracker);
90+ }
91+
92+ @Override
93+ public Cluster unregister(LatencyTracker tracker) {
94+ return delegate().unregister(tracker);
95+ }
96+
97+ @Override
98+ public CloseFuture closeAsync() {
99+ return delegate().closeAsync();
100+ }
101+
102+ @Override
103+ public void close() {
104+ delegate().close();
105+ }
106+
107+ @Override
108+ public boolean isClosed() {
109+ return delegate().isClosed();
110+ }
111+}
added driver-core/src/test/java/com/datastax/driver/core/ClusterDelegateTest.java +38 −0
@@ -0,0 +1,38 @@
1+package com.datastax.driver.core;
2+
3+import java.util.Collection;
4+
5+import com.google.common.collect.Lists;
6+import org.testng.annotations.Test;
7+
8+import static org.assertj.core.api.Assertions.assertThat;
9+
10+public class ClusterDelegateTest extends CCMBridge.PerClassSingleNodeCluster {
11+ @Override
12+ protected Collection<String> getTableDefinitions() {
13+ return Lists.newArrayList();
14+ }
15+
16+ @Test(groups = "short")
17+ public void should_allow_subclass_to_delegate_to_other_instance() {
18+ SimpleDelegatingCluster delegatingCluster = new SimpleDelegatingCluster(cluster);
19+
20+ ResultSet rs = delegatingCluster.connect().execute("select * from system.local");
21+
22+ assertThat(rs.all()).hasSize(1);
23+ }
24+
25+ static class SimpleDelegatingCluster extends DelegatingCluster {
26+
27+ private final Cluster delegate;
28+
29+ public SimpleDelegatingCluster(Cluster delegate) {
30+ this.delegate = delegate;
31+ }
32+
33+ @Override
34+ protected Cluster delegate() {
35+ return delegate;
36+ }
37+ }
38+}