Home | History | Annotate | Download | only in benchmarks
      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  */
     16 package com.squareup.okhttp.benchmarks;
     17 
     18 import com.squareup.okhttp.HttpUrl;
     19 import java.io.IOException;
     20 import java.io.InputStream;
     21 import java.util.concurrent.LinkedBlockingQueue;
     22 import java.util.concurrent.ThreadPoolExecutor;
     23 import java.util.concurrent.TimeUnit;
     24 
     25 /** Any HTTP client with a blocking API. */
     26 abstract 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(HttpUrl 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(HttpUrl url);
     55 }
     56