You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

InterruptTimer.java 6.5KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234
  1. /*
  2. * Copyright (C) 2009, Google Inc.
  3. * and other copyright owners as documented in the project's IP log.
  4. *
  5. * This program and the accompanying materials are made available
  6. * under the terms of the Eclipse Distribution License v1.0 which
  7. * accompanies this distribution, is reproduced below, and is
  8. * available at http://www.eclipse.org/org/documents/edl-v10.php
  9. *
  10. * All rights reserved.
  11. *
  12. * Redistribution and use in source and binary forms, with or
  13. * without modification, are permitted provided that the following
  14. * conditions are met:
  15. *
  16. * - Redistributions of source code must retain the above copyright
  17. * notice, this list of conditions and the following disclaimer.
  18. *
  19. * - Redistributions in binary form must reproduce the above
  20. * copyright notice, this list of conditions and the following
  21. * disclaimer in the documentation and/or other materials provided
  22. * with the distribution.
  23. *
  24. * - Neither the name of the Eclipse Foundation, Inc. nor the
  25. * names of its contributors may be used to endorse or promote
  26. * products derived from this software without specific prior
  27. * written permission.
  28. *
  29. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
  30. * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
  31. * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
  32. * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  33. * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
  34. * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  35. * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
  36. * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  37. * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  38. * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
  39. * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  40. * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
  41. * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  42. */
  43. package org.eclipse.jgit.util.io;
  44. import java.text.MessageFormat;
  45. import org.eclipse.jgit.internal.JGitText;
  46. /**
  47. * Triggers an interrupt on the calling thread if it doesn't complete a block.
  48. * <p>
  49. * Classes can use this to trip an alarm interrupting the calling thread if it
  50. * doesn't complete a block within the specified timeout. Typical calling
  51. * pattern is:
  52. *
  53. * <pre>
  54. * private InterruptTimer myTimer = ...;
  55. * void foo() {
  56. * try {
  57. * myTimer.begin(timeout);
  58. * // work
  59. * } finally {
  60. * myTimer.end();
  61. * }
  62. * }
  63. * </pre>
  64. * <p>
  65. * An InterruptTimer is not recursive. To implement recursive timers,
  66. * independent InterruptTimer instances are required. A single InterruptTimer
  67. * may be shared between objects which won't recursively call each other.
  68. * <p>
  69. * Each InterruptTimer spawns one background thread to sleep the specified time
  70. * and interrupt the thread which called {@link #begin(int)}. It is up to the
  71. * caller to ensure that the operations within the work block between the
  72. * matched begin and end calls tests the interrupt flag (most IO operations do).
  73. * <p>
  74. * To terminate the background thread, use {@link #terminate()}. If the
  75. * application fails to terminate the thread, it will (eventually) terminate
  76. * itself when the InterruptTimer instance is garbage collected.
  77. *
  78. * @see TimeoutInputStream
  79. */
  80. public final class InterruptTimer {
  81. private final AlarmState state;
  82. private final AlarmThread thread;
  83. final AutoKiller autoKiller;
  84. /**
  85. * Create a new timer with a default thread name.
  86. */
  87. public InterruptTimer() {
  88. this("JGit-InterruptTimer"); //$NON-NLS-1$
  89. }
  90. /**
  91. * Create a new timer to signal on interrupt on the caller.
  92. * <p>
  93. * The timer thread is created in the calling thread's ThreadGroup.
  94. *
  95. * @param threadName
  96. * name of the timer thread.
  97. */
  98. public InterruptTimer(final String threadName) {
  99. state = new AlarmState();
  100. autoKiller = new AutoKiller(state);
  101. thread = new AlarmThread(threadName, state);
  102. thread.start();
  103. }
  104. /**
  105. * Arm the interrupt timer before entering a blocking operation.
  106. *
  107. * @param timeout
  108. * number of milliseconds before the interrupt should trigger.
  109. * Must be &gt; 0.
  110. */
  111. public void begin(final int timeout) {
  112. if (timeout <= 0)
  113. throw new IllegalArgumentException(MessageFormat.format(
  114. JGitText.get().invalidTimeout, Integer.valueOf(timeout)));
  115. Thread.interrupted();
  116. state.begin(timeout);
  117. }
  118. /**
  119. * Disable the interrupt timer, as the operation is complete.
  120. */
  121. public void end() {
  122. state.end();
  123. }
  124. /**
  125. * Shutdown the timer thread, and wait for it to terminate.
  126. */
  127. public void terminate() {
  128. state.terminate();
  129. try {
  130. thread.join();
  131. } catch (InterruptedException e) {
  132. //
  133. }
  134. }
  135. static final class AlarmThread extends Thread {
  136. AlarmThread(final String name, final AlarmState q) {
  137. super(q);
  138. setName(name);
  139. setDaemon(true);
  140. }
  141. }
  142. // The trick here is, the AlarmThread does not have a reference to the
  143. // AutoKiller instance, only the InterruptTimer itself does. Thus when
  144. // the InterruptTimer is GC'd, the AutoKiller is also unreachable and
  145. // can be GC'd. When it gets finalized, it tells the AlarmThread to
  146. // terminate, triggering the thread to exit gracefully.
  147. //
  148. private static final class AutoKiller {
  149. private final AlarmState state;
  150. AutoKiller(final AlarmState s) {
  151. state = s;
  152. }
  153. @Override
  154. protected void finalize() throws Throwable {
  155. state.terminate();
  156. }
  157. }
  158. static final class AlarmState implements Runnable {
  159. private Thread callingThread;
  160. private long deadline;
  161. private boolean terminated;
  162. AlarmState() {
  163. callingThread = Thread.currentThread();
  164. }
  165. @Override
  166. public synchronized void run() {
  167. while (!terminated && callingThread.isAlive()) {
  168. try {
  169. if (0 < deadline) {
  170. final long delay = deadline - now();
  171. if (delay <= 0) {
  172. deadline = 0;
  173. callingThread.interrupt();
  174. } else {
  175. wait(delay);
  176. }
  177. } else {
  178. wait(1000);
  179. }
  180. } catch (InterruptedException e) {
  181. // Treat an interrupt as notice to examine state.
  182. }
  183. }
  184. }
  185. synchronized void begin(final int timeout) {
  186. if (terminated)
  187. throw new IllegalStateException(JGitText.get().timerAlreadyTerminated);
  188. callingThread = Thread.currentThread();
  189. deadline = now() + timeout;
  190. notifyAll();
  191. }
  192. synchronized void end() {
  193. if (0 == deadline)
  194. Thread.interrupted();
  195. else
  196. deadline = 0;
  197. notifyAll();
  198. }
  199. synchronized void terminate() {
  200. if (!terminated) {
  201. deadline = 0;
  202. terminated = true;
  203. notifyAll();
  204. }
  205. }
  206. private static long now() {
  207. return System.currentTimeMillis();
  208. }
  209. }
  210. }