1/* 2 * Copyright (C) 2012 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.internal.spdy; 17 18import java.util.concurrent.CountDownLatch; 19import java.util.concurrent.TimeUnit; 20 21/** 22 * A locally-originated ping. 23 */ 24public final class Ping { 25 private final CountDownLatch latch = new CountDownLatch(1); 26 private long sent = -1; 27 private long received = -1; 28 29 Ping() { 30 } 31 32 void send() { 33 if (sent != -1) throw new IllegalStateException(); 34 sent = System.nanoTime(); 35 } 36 37 void receive() { 38 if (received != -1 || sent == -1) throw new IllegalStateException(); 39 received = System.nanoTime(); 40 latch.countDown(); 41 } 42 43 void cancel() { 44 if (received != -1 || sent == -1) throw new IllegalStateException(); 45 received = sent - 1; 46 latch.countDown(); 47 } 48 49 /** 50 * Returns the round trip time for this ping in nanoseconds, waiting for the 51 * response to arrive if necessary. Returns -1 if the response was 52 * cancelled. 53 */ 54 public long roundTripTime() throws InterruptedException { 55 latch.await(); 56 return received - sent; 57 } 58 59 /** 60 * Returns the round trip time for this ping in nanoseconds, or -1 if the 61 * response was cancelled, or -2 if the timeout elapsed before the round 62 * trip completed. 63 */ 64 public long roundTripTime(long timeout, TimeUnit unit) throws InterruptedException { 65 if (latch.await(timeout, unit)) { 66 return received - sent; 67 } else { 68 return -2; 69 } 70 } 71} 72