1/*
2 * Copyright (C) 2014 Square, 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.squareup.okhttp.benchmarks;
17
18import java.io.IOException;
19import java.io.InputStream;
20import java.net.URL;
21import java.util.concurrent.LinkedBlockingQueue;
22import java.util.concurrent.ThreadPoolExecutor;
23import java.util.concurrent.TimeUnit;
24
25/** Any HTTP client with a blocking API. */
26abstract class SynchronousHttpClient implements HttpClient {
27  ThreadPoolExecutor executor;
28  int targetBacklog;
29
30  @Override public void prepare(Benchmark benchmark) {
31    this.targetBacklog = benchmark.targetBacklog;
32    executor = new ThreadPoolExecutor(benchmark.concurrencyLevel, benchmark.concurrencyLevel,
33        1, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>());
34  }
35
36  @Override public void enqueue(URL url) {
37    executor.execute(request(url));
38  }
39
40  @Override public boolean acceptingJobs() {
41    return executor.getQueue().size() < targetBacklog;
42  }
43
44  static long readAllAndClose(InputStream in) throws IOException {
45    byte[] buffer = new byte[1024];
46    long total = 0;
47    for (int count; (count = in.read(buffer)) != -1; ) {
48      total += count;
49    }
50    in.close();
51    return total;
52  }
53
54  abstract Runnable request(URL url);
55}
56