001/*
002 * Copyright (C) 2011 The Guava Authors
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 *
008 * http://www.apache.org/licenses/LICENSE-2.0
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 */
016
017package com.google.common.util.concurrent;
018
019import static java.util.concurrent.TimeUnit.NANOSECONDS;
020
021import com.google.common.annotations.Beta;
022import com.google.common.base.Preconditions;
023
024import java.util.concurrent.BlockingQueue;
025import java.util.concurrent.CountDownLatch;
026import java.util.concurrent.ExecutionException;
027import java.util.concurrent.Future;
028import java.util.concurrent.TimeUnit;
029import java.util.concurrent.TimeoutException;
030
031/**
032 * Utilities for treating interruptible operations as uninterruptible.
033 * In all cases, if a thread is interrupted during such a call, the call
034 * continues to block until the result is available or the timeout elapses,
035 * and only then re-interrupts the thread.
036 *
037 * @author Anthony Zana
038 * @since 10.0
039 */
040@Beta
041public final class Uninterruptibles {
042
043  // Implementation Note: As of 3-7-11, the logic for each blocking/timeout
044  // methods is identical, save for method being invoked.
045
046  /**
047   * Invokes {@code latch.}{@link CountDownLatch#await() await()}
048   * uninterruptibly.
049   */
050  public static void awaitUninterruptibly(CountDownLatch latch) {
051    boolean interrupted = false;
052    try {
053      while (true) {
054        try {
055          latch.await();
056          return;
057        } catch (InterruptedException e) {
058          interrupted = true;
059        }
060      }
061    } finally {
062      if (interrupted) {
063        Thread.currentThread().interrupt();
064      }
065    }
066  }
067
068  /**
069   * Invokes
070   * {@code latch.}{@link CountDownLatch#await(long, TimeUnit)
071   * await(timeout, unit)} uninterruptibly.
072   */
073  public static boolean awaitUninterruptibly(CountDownLatch latch,
074      long timeout, TimeUnit unit) {
075    boolean interrupted = false;
076    try {
077      long remainingNanos = unit.toNanos(timeout);
078      long end = System.nanoTime() + remainingNanos;
079
080      while (true) {
081        try {
082          // CountDownLatch treats negative timeouts just like zero.
083          return latch.await(remainingNanos, NANOSECONDS);
084        } catch (InterruptedException e) {
085          interrupted = true;
086          remainingNanos = end - System.nanoTime();
087        }
088      }
089    } finally {
090      if (interrupted) {
091        Thread.currentThread().interrupt();
092      }
093    }
094  }
095
096  /**
097   * Invokes {@code toJoin.}{@link Thread#join() join()} uninterruptibly.
098   */
099  public static void joinUninterruptibly(Thread toJoin) {
100    boolean interrupted = false;
101    try {
102      while (true) {
103        try {
104          toJoin.join();
105          return;
106        } catch (InterruptedException e) {
107          interrupted = true;
108        }
109      }
110    } finally {
111      if (interrupted) {
112        Thread.currentThread().interrupt();
113      }
114    }
115  }
116
117  /**
118   * Invokes {@code future.}{@link Future#get() get()} uninterruptibly.
119   * To get uninterruptibility and remove checked exceptions, see
120   * {@link Futures#getUnchecked}.
121   *
122   * <p>If instead, you wish to treat {@link InterruptedException} uniformly
123   * with other exceptions, see {@link Futures#get(Future, Class) Futures.get}
124   * or {@link Futures#makeChecked}.
125   *
126   * @throws ExecutionException if the computation threw an exception
127   * @throws CancellationException if the computation was cancelled
128   */
129  public static <V> V getUninterruptibly(Future<V> future)
130      throws ExecutionException {
131    boolean interrupted = false;
132    try {
133      while (true) {
134        try {
135          return future.get();
136        } catch (InterruptedException e) {
137          interrupted = true;
138        }
139      }
140    } finally {
141      if (interrupted) {
142        Thread.currentThread().interrupt();
143      }
144    }
145  }
146
147  /**
148   * Invokes
149   * {@code future.}{@link Future#get(long, TimeUnit) get(timeout, unit)}
150   * uninterruptibly.
151   *
152   * <p>If instead, you wish to treat {@link InterruptedException} uniformly
153   * with other exceptions, see {@link Futures#get(Future, Class) Futures.get}
154   * or {@link Futures#makeChecked}.
155   *
156   * @throws ExecutionException if the computation threw an exception
157   * @throws CancellationException if the computation was cancelled
158   * @throws TimeoutException if the wait timed out
159   */
160  public static <V> V getUninterruptibly(
161      Future<V> future, long timeout,  TimeUnit unit)
162          throws ExecutionException, TimeoutException {
163    boolean interrupted = false;
164    try {
165      long remainingNanos = unit.toNanos(timeout);
166      long end = System.nanoTime() + remainingNanos;
167
168      while (true) {
169        try {
170          // Future treats negative timeouts just like zero.
171          return future.get(remainingNanos, NANOSECONDS);
172        } catch (InterruptedException e) {
173          interrupted = true;
174          remainingNanos = end - System.nanoTime();
175        }
176      }
177    } finally {
178      if (interrupted) {
179        Thread.currentThread().interrupt();
180      }
181    }
182  }
183
184  /**
185   * Invokes
186   * {@code unit.}{@link TimeUnit#timedJoin(Thread, long)
187   * timedJoin(toJoin, timeout)} uninterruptibly.
188   */
189  public static void joinUninterruptibly(Thread toJoin,
190      long timeout, TimeUnit unit) {
191    Preconditions.checkNotNull(toJoin);
192    boolean interrupted = false;
193    try {
194      long remainingNanos = unit.toNanos(timeout);
195      long end = System.nanoTime() + remainingNanos;
196      while (true) {
197        try {
198          // TimeUnit.timedJoin() treats negative timeouts just like zero.
199          NANOSECONDS.timedJoin(toJoin, remainingNanos);
200          return;
201        } catch (InterruptedException e) {
202          interrupted = true;
203          remainingNanos = end - System.nanoTime();
204        }
205      }
206    } finally {
207      if (interrupted) {
208        Thread.currentThread().interrupt();
209      }
210    }
211  }
212
213  /**
214   * Invokes {@code queue.}{@link BlockingQueue#take() take()} uninterruptibly.
215   */
216  public static <E> E takeUninterruptibly(BlockingQueue<E> queue) {
217    boolean interrupted = false;
218    try {
219      while (true) {
220        try {
221          return queue.take();
222        } catch (InterruptedException e) {
223          interrupted = true;
224        }
225      }
226    } finally {
227      if (interrupted) {
228        Thread.currentThread().interrupt();
229      }
230    }
231  }
232
233  /**
234   * Invokes {@code queue.}{@link BlockingQueue#put(Object) put(element)}
235   * uninterruptibly.
236   *
237   * @throws ClassCastException if the class of the specified element prevents
238   *     it from being added to the given queue
239   * @throws IllegalArgumentException if some property of the specified element
240   *     prevents it from being added to the given queue
241   */
242  public static <E> void putUninterruptibly(BlockingQueue<E> queue, E element) {
243    boolean interrupted = false;
244    try {
245      while (true) {
246        try {
247          queue.put(element);
248          return;
249        } catch (InterruptedException e) {
250          interrupted = true;
251        }
252      }
253    } finally {
254      if (interrupted) {
255        Thread.currentThread().interrupt();
256      }
257    }
258  }
259
260  // TODO(user): Support Sleeper somehow (wrapper or interface method)?
261  /**
262   * Invokes {@code unit.}{@link TimeUnit#sleep(long) sleep(sleepFor)}
263   * uninterruptibly.
264   */
265  public static void sleepUninterruptibly(long sleepFor, TimeUnit unit) {
266    boolean interrupted = false;
267    try {
268      long remainingNanos = unit.toNanos(sleepFor);
269      long end = System.nanoTime() + remainingNanos;
270      while (true) {
271        try {
272          // TimeUnit.sleep() treats negative timeouts just like zero.
273          NANOSECONDS.sleep(remainingNanos);
274          return;
275        } catch (InterruptedException e) {
276          interrupted = true;
277          remainingNanos = end - System.nanoTime();
278        }
279      }
280    } finally {
281      if (interrupted) {
282        Thread.currentThread().interrupt();
283      }
284    }
285  }
286
287  // TODO(user): Add support for waitUninterruptibly.
288
289  private Uninterruptibles() {}
290}