Home | History | Annotate | Download | only in okio
      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 okio;
     17 
     18 import java.io.IOException;
     19 import java.io.InterruptedIOException;
     20 import java.util.concurrent.TimeUnit;
     21 
     22 /**
     23  * The time that a requested operation is due. If the deadline is reached before
     24  * the operation has completed, the operation should be aborted.
     25  */
     26 public class Deadline {
     27   public static final Deadline NONE = new Deadline() {
     28     @Override public Deadline start(long timeout, TimeUnit unit) {
     29       throw new UnsupportedOperationException();
     30     }
     31 
     32     @Override public boolean reached() {
     33       return false;
     34     }
     35   };
     36 
     37   private long deadlineNanos;
     38 
     39   public Deadline() {
     40   }
     41 
     42   public Deadline start(long timeout, TimeUnit unit) {
     43     deadlineNanos = System.nanoTime() + unit.toNanos(timeout);
     44     return this;
     45   }
     46 
     47   public boolean reached() {
     48     return System.nanoTime() - deadlineNanos >= 0; // Subtract to avoid overflow!
     49   }
     50 
     51   public final void throwIfReached() throws IOException {
     52     // TODO: a more catchable exception type?
     53     if (reached()) throw new IOException("Deadline reached");
     54 
     55     // If the thread is interrupted, do not proceed with further I/O.
     56     if (Thread.interrupted()) throw new InterruptedIOException();
     57   }
     58 }
     59