Sync.java revision 672:2bb058ce572e
1/*
2 * Copyright (c) 2001, 2002, Oracle and/or its affiliates. All rights reserved.
3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4 *
5 * This code is free software; you can redistribute it and/or modify it
6 * under the terms of the GNU General Public License version 2 only, as
7 * published by the Free Software Foundation.  Oracle designates this
8 * particular file as subject to the "Classpath" exception as provided
9 * by Oracle in the LICENSE file that accompanied this code.
10 *
11 * This code is distributed in the hope that it will be useful, but WITHOUT
12 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
13 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
14 * version 2 for more details (a copy is included in the LICENSE file that
15 * accompanied this code).
16 *
17 * You should have received a copy of the GNU General Public License version
18 * 2 along with this work; if not, write to the Free Software Foundation,
19 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
20 *
21 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
22 * or visit www.oracle.com if you need additional information or have any
23 * questions.
24 */
25
26/*
27  File: Sync.java
28
29  Originally written by Doug Lea and released into the public domain.
30  This may be used for any purposes whatsoever without acknowledgment.
31  Thanks for the assistance and support of Sun Microsystems Labs,
32  and everyone contributing, testing, and using this code.
33
34  History:
35  Date       Who                What
36  11Jun1998  dl               Create public version
37   5Aug1998  dl               Added some convenient time constants
38*/
39
40package com.sun.corba.se.impl.orbutil.concurrent;
41
42/**
43 * Main interface for locks, gates, and conditions.
44 * <p>
45 * Sync objects isolate waiting and notification for particular
46 * logical states, resource availability, events, and the like that are
47 * shared across multiple threads. Use of Syncs sometimes
48 * (but by no means always) adds flexibility and efficiency
49 * compared to the use of plain java monitor methods
50 * and locking, and are sometimes (but by no means always)
51 * simpler to program with.
52 * <p>
53 *
54 * Most Syncs are intended to be used primarily (although
55 * not exclusively) in  before/after constructions such as:
56 * <pre>
57 * class X {
58 *   Sync gate;
59 *   // ...
60 *
61 *   public void m() {
62 *     try {
63 *       gate.acquire();  // block until condition holds
64 *       try {
65 *         // ... method body
66 *       }
67 *       finally {
68 *         gate.release()
69 *       }
70 *     }
71 *     catch (InterruptedException ex) {
72 *       // ... evasive action
73 *     }
74 *   }
75 *
76 *   public void m2(Sync cond) { // use supplied condition
77 *     try {
78 *       if (cond.attempt(10)) {         // try the condition for 10 ms
79 *         try {
80 *           // ... method body
81 *         }
82 *         finally {
83 *           cond.release()
84 *         }
85 *       }
86 *     }
87 *     catch (InterruptedException ex) {
88 *       // ... evasive action
89 *     }
90 *   }
91 * }
92 * </pre>
93 * Syncs may be used in somewhat tedious but more flexible replacements
94 * for built-in Java synchronized blocks. For example:
95 * <pre>
96 * class HandSynched {
97 *   private double state_ = 0.0;
98 *   private final Sync lock;  // use lock type supplied in constructor
99 *   public HandSynched(Sync l) { lock = l; }
100 *
101 *   public void changeState(double d) {
102 *     try {
103 *       lock.acquire();
104 *       try     { state_ = updateFunction(d); }
105 *       finally { lock.release(); }
106 *     }
107 *     catch(InterruptedException ex) { }
108 *   }
109 *
110 *   public double getState() {
111 *     double d = 0.0;
112 *     try {
113 *       lock.acquire();
114 *       try     { d = accessFunction(state_); }
115 *       finally { lock.release(); }
116 *     }
117 *     catch(InterruptedException ex){}
118 *     return d;
119 *   }
120 *   private double updateFunction(double d) { ... }
121 *   private double accessFunction(double d) { ... }
122 * }
123 * </pre>
124 * If you have a lot of such methods, and they take a common
125 * form, you can standardize this using wrappers. Some of these
126 * wrappers are standardized in LockedExecutor, but you can make others.
127 * For example:
128 * <pre>
129 * class HandSynchedV2 {
130 *   private double state_ = 0.0;
131 *   private final Sync lock;  // use lock type supplied in constructor
132 *   public HandSynchedV2(Sync l) { lock = l; }
133 *
134 *   protected void runSafely(Runnable r) {
135 *     try {
136 *       lock.acquire();
137 *       try { r.run(); }
138 *       finally { lock.release(); }
139 *     }
140 *     catch (InterruptedException ex) { // propagate without throwing
141 *       Thread.currentThread().interrupt();
142 *     }
143 *   }
144 *
145 *   public void changeState(double d) {
146 *     runSafely(new Runnable() {
147 *       public void run() { state_ = updateFunction(d); }
148 *     });
149 *   }
150 *   // ...
151 * }
152 * </pre>
153 * <p>
154 * One reason to bother with such constructions is to use deadlock-
155 * avoiding back-offs when dealing with locks involving multiple objects.
156 * For example, here is a Cell class that uses attempt to back-off
157 * and retry if two Cells are trying to swap values with each other
158 * at the same time.
159 * <pre>
160 * class Cell {
161 *   long value;
162 *   Sync lock = ... // some sync implementation class
163 *   void swapValue(Cell other) {
164 *     for (;;) {
165 *       try {
166 *         lock.acquire();
167 *         try {
168 *           if (other.lock.attempt(100)) {
169 *             try {
170 *               long t = value;
171 *               value = other.value;
172 *               other.value = t;
173 *               return;
174 *             }
175 *             finally { other.lock.release(); }
176 *           }
177 *         }
178 *         finally { lock.release(); }
179 *       }
180 *       catch (InterruptedException ex) { return; }
181 *     }
182 *   }
183 * }
184 *</pre>
185 * <p>
186 * Here is an even fancier version, that uses lock re-ordering
187 * upon conflict:
188 * <pre>
189 * class Cell {
190 *   long value;
191 *   Sync lock = ...;
192 *   private static boolean trySwap(Cell a, Cell b) {
193 *     a.lock.acquire();
194 *     try {
195 *       if (!b.lock.attempt(0))
196 *         return false;
197 *       try {
198 *         long t = a.value;
199 *         a.value = b.value;
200 *         b.value = t;
201 *         return true;
202 *       }
203 *       finally { other.lock.release(); }
204 *     }
205 *     finally { lock.release(); }
206 *     return false;
207 *   }
208 *
209 *  void swapValue(Cell other) {
210 *    try {
211 *      while (!trySwap(this, other) &&
212 *            !tryswap(other, this))
213 *        Thread.sleep(1);
214 *    }
215 *    catch (InterruptedException ex) { return; }
216 *  }
217 *}
218 *</pre>
219 * <p>
220 * Interruptions are in general handled as early as possible.
221 * Normally, InterruptionExceptions are thrown
222 * in acquire and attempt(msec) if interruption
223 * is detected upon entry to the method, as well as in any
224 * later context surrounding waits.
225 * However, interruption status is ignored in release();
226 * <p>
227 * Timed versions of attempt report failure via return value.
228 * If so desired, you can transform such constructions to use exception
229 * throws via
230 * <pre>
231 *   if (!c.attempt(timeval)) throw new TimeoutException(timeval);
232 * </pre>
233 * <p>
234 * The TimoutSync wrapper class can be used to automate such usages.
235 * <p>
236 * All time values are expressed in milliseconds as longs, which have a maximum
237 * value of Long.MAX_VALUE, or almost 300,000 centuries. It is not
238 * known whether JVMs actually deal correctly with such extreme values.
239 * For convenience, some useful time values are defined as static constants.
240 * <p>
241 * All implementations of the three Sync methods guarantee to
242 * somehow employ Java <code>synchronized</code> methods or blocks,
243 * and so entail the memory operations described in JLS
244 * chapter 17 which ensure that variables are loaded and flushed
245 * within before/after constructions.
246 * <p>
247 * Syncs may also be used in spinlock constructions. Although
248 * it is normally best to just use acquire(), various forms
249 * of busy waits can be implemented. For a simple example
250 * (but one that would probably never be preferable to using acquire()):
251 * <pre>
252 * class X {
253 *   Sync lock = ...
254 *   void spinUntilAcquired() throws InterruptedException {
255 *     // Two phase.
256 *     // First spin without pausing.
257 *     int purespins = 10;
258 *     for (int i = 0; i < purespins; ++i) {
259 *       if (lock.attempt(0))
260 *         return true;
261 *     }
262 *     // Second phase - use timed waits
263 *     long waitTime = 1; // 1 millisecond
264 *     for (;;) {
265 *       if (lock.attempt(waitTime))
266 *         return true;
267 *       else
268 *         waitTime = waitTime * 3 / 2 + 1; // increase 50%
269 *     }
270 *   }
271 * }
272 * </pre>
273 * <p>
274 * In addition pure synchronization control, Syncs
275 * may be useful in any context requiring before/after methods.
276 * For example, you can use an ObservableSync
277 * (perhaps as part of a LayeredSync) in order to obtain callbacks
278 * before and after each method invocation for a given class.
279 *
280 * <p>[<a href="http://gee.cs.oswego.edu/dl/classes/EDU/oswego/cs/dl/util/concurrent/intro.html"> Introduction to this package. </a>]
281 **/
282
283
284public interface Sync {
285
286  /**
287   *  Wait (possibly forever) until successful passage.
288   *  Fail only upon interuption. Interruptions always result in
289   *  `clean' failures. On failure,  you can be sure that it has not
290   *  been acquired, and that no
291   *  corresponding release should be performed. Conversely,
292   *  a normal return guarantees that the acquire was successful.
293  **/
294
295  public void acquire() throws InterruptedException;
296
297  /**
298   * Wait at most msecs to pass; report whether passed.
299   * <p>
300   * The method has best-effort semantics:
301   * The msecs bound cannot
302   * be guaranteed to be a precise upper bound on wait time in Java.
303   * Implementations generally can only attempt to return as soon as possible
304   * after the specified bound. Also, timers in Java do not stop during garbage
305   * collection, so timeouts can occur just because a GC intervened.
306   * So, msecs arguments should be used in
307   * a coarse-grained manner. Further,
308   * implementations cannot always guarantee that this method
309   * will return at all without blocking indefinitely when used in
310   * unintended ways. For example, deadlocks may be encountered
311   * when called in an unintended context.
312   * <p>
313   * @param msecs the number of milleseconds to wait.
314   * An argument less than or equal to zero means not to wait at all.
315   * However, this may still require
316   * access to a synchronization lock, which can impose unbounded
317   * delay if there is a lot of contention among threads.
318   * @return true if acquired
319  **/
320
321  public boolean attempt(long msecs) throws InterruptedException;
322
323  /**
324   * Potentially enable others to pass.
325   * <p>
326   * Because release does not raise exceptions,
327   * it can be used in `finally' clauses without requiring extra
328   * embedded try/catch blocks. But keep in mind that
329   * as with any java method, implementations may
330   * still throw unchecked exceptions such as Error or NullPointerException
331   * when faced with uncontinuable errors. However, these should normally
332   * only be caught by higher-level error handlers.
333  **/
334
335  public void release();
336
337  /**  One second, in milliseconds; convenient as a time-out value **/
338  public static final long ONE_SECOND = 1000;
339
340  /**  One minute, in milliseconds; convenient as a time-out value **/
341  public static final long ONE_MINUTE = 60 * ONE_SECOND;
342
343  /**  One hour, in milliseconds; convenient as a time-out value **/
344  public static final long ONE_HOUR = 60 * ONE_MINUTE;
345
346  /**  One day, in milliseconds; convenient as a time-out value **/
347  public static final long ONE_DAY = 24 * ONE_HOUR;
348
349  /**  One week, in milliseconds; convenient as a time-out value **/
350  public static final long ONE_WEEK = 7 * ONE_DAY;
351
352  /**  One year in milliseconds; convenient as a time-out value  **/
353  // Not that it matters, but there is some variation across
354  // standard sources about value at msec precision.
355  // The value used is the same as in java.util.GregorianCalendar
356  public static final long ONE_YEAR = (long)(365.2425 * ONE_DAY);
357
358  /**  One century in milliseconds; convenient as a time-out value **/
359  public static final long ONE_CENTURY = 100 * ONE_YEAR;
360
361
362}
363