Elffuss BraidHub

kikocis/java-driver public

d4015c5defee · 2.2 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;
19
20import com.google.common.util.concurrent.Uninterruptibles;
21
22import com.datastax.driver.core.Session;
23import com.datastax.driver.core.exceptions.DriverException;
24
25public class BlockingConsumer implements Consumer {
26
27 private final Runner runner = new Runner();
28
29 private final Session session;
30 private final QueryGenerator requests;
31 private final Reporter reporter;
32
33 public BlockingConsumer(Session session,
34 QueryGenerator requests,
35 Reporter reporter) {
36 this.session = session;
37 this.requests = requests;
38 this.reporter = reporter;
39 this.runner.setDaemon(true);
40 }
41
42 @Override
43 public void start() {
44 this.runner.start();
45 }
46
47 @Override
48 public void join() {
49 Uninterruptibles.joinUninterruptibly(this.runner);
50 }
51
52 private class Runner extends Thread {
53
54 public Runner() {
55 super("Consumer Threads");
56 }
57
58 public void run() {
59 try {
60 while (requests.hasNext())
61 handle(requests.next());
62 } catch (DriverException e) {
63 System.err.println("Error during query: " + e.getMessage());
64 }
65 }
66
67 protected void handle(QueryGenerator.Request request) {
68 Reporter.Context ctx = reporter.newRequest();
69 try {
70 request.execute(session);
71 } finally {
72 ctx.done();
73 }
74 }
75 }
76}