Elffuss BraidHub

kikocis/java-driver public

56ea1f21527e · 3.0 KiBRawPermalink
1/*
2 * Copyright (C) 2012-2015 DataStax Inc.
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16package com.datastax.driver.stress;
17
18import java.util.Iterator;
19import java.util.concurrent.CountDownLatch;
20import java.util.concurrent.ExecutorService;
21import java.util.concurrent.Executors;
22
23import com.google.common.util.concurrent.FutureCallback;
24import com.google.common.util.concurrent.Futures;
25
26import com.datastax.driver.core.ResultSet;
27import com.datastax.driver.core.ResultSetFuture;
28import com.datastax.driver.core.Session;
29
30import static com.google.common.util.concurrent.Uninterruptibles.awaitUninterruptibly;
31
32public class AsynchronousConsumer implements Consumer {
33
34 private static final ExecutorService executorService = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());
35
36 private final CountDownLatch shutdownLatch = new CountDownLatch(1);
37
38 private final Session session;
39 private final QueryGenerator requests;
40 private final Reporter reporter;
41
42 public AsynchronousConsumer(Session session,
43 QueryGenerator requests,
44 Reporter reporter) {
45 this.session = session;
46 this.requests = requests;
47 this.reporter = reporter;
48 }
49
50 @Override
51 public void start() {
52 executorService.execute(new Runnable() {
53 @Override
54 public void run() {
55 request();
56 }
57 });
58 }
59
60 private void request() {
61
62 if (!requests.hasNext()) {
63 shutdown();
64 return;
65 }
66
67 handle(requests.next());
68 }
69
70 @Override
71 public void join() {
72 awaitUninterruptibly(shutdownLatch);
73 }
74
75 protected void handle(QueryGenerator.Request request) {
76
77 final Reporter.Context ctx = reporter.newRequest();
78
79 ResultSetFuture resultSetFuture = request.executeAsync(session);
80 Futures.addCallback(resultSetFuture, new FutureCallback<ResultSet>() {
81 @Override
82 public void onSuccess(final ResultSet result) {
83 ctx.done();
84 request();
85 }
86
87 @Override
88 public void onFailure(final Throwable t) {
89 // Could do better I suppose
90 System.err.println("Error during request: " + t);
91 ctx.done();
92 request();
93 }
94 }, executorService);
95 }
96
97 protected void shutdown() {
98 shutdownLatch.countDown();
99 }
100}