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 
  40 package 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  * <p>
 280 
 281  * <p>[<a href="http://gee.cs.oswego.edu/dl/classes/EDU/oswego/cs/dl/util/concurrent/intro.html"> Introduction to this package. </a>]
 282 **/
 283 
 284 
 285 public interface Sync {
 286 
 287   /**
 288    *  Wait (possibly forever) until successful passage.
 289    *  Fail only upon interuption. Interruptions always result in
 290    *  `clean' failures. On failure,  you can be sure that it has not
 291    *  been acquired, and that no
 292    *  corresponding release should be performed. Conversely,
 293    *  a normal return guarantees that the acquire was successful.
 294   **/
 295 
 296   public void acquire() throws InterruptedException;
 297 
 298   /**
 299    * Wait at most msecs to pass; report whether passed.
 300    * <p>
 301    * The method has best-effort semantics:
 302    * The msecs bound cannot
 303    * be guaranteed to be a precise upper bound on wait time in Java.
 304    * Implementations generally can only attempt to return as soon as possible
 305    * after the specified bound. Also, timers in Java do not stop during garbage
 306    * collection, so timeouts can occur just because a GC intervened.
 307    * So, msecs arguments should be used in
 308    * a coarse-grained manner. Further,
 309    * implementations cannot always guarantee that this method
 310    * will return at all without blocking indefinitely when used in
 311    * unintended ways. For example, deadlocks may be encountered
 312    * when called in an unintended context.
 313    * <p>
 314    * @param msecs the number of milleseconds to wait.
 315    * An argument less than or equal to zero means not to wait at all.
 316    * However, this may still require
 317    * access to a synchronization lock, which can impose unbounded
 318    * delay if there is a lot of contention among threads.
 319    * @return true if acquired
 320   **/
 321 
 322   public boolean attempt(long msecs) throws InterruptedException;
 323 
 324   /**
 325    * Potentially enable others to pass.
 326    * <p>
 327    * Because release does not raise exceptions,
 328    * it can be used in `finally' clauses without requiring extra
 329    * embedded try/catch blocks. But keep in mind that
 330    * as with any java method, implementations may
 331    * still throw unchecked exceptions such as Error or NullPointerException
 332    * when faced with uncontinuable errors. However, these should normally
 333    * only be caught by higher-level error handlers.
 334   **/
 335 
 336   public void release();
 337 
 338   /**  One second, in milliseconds; convenient as a time-out value **/
 339   public static final long ONE_SECOND = 1000;
 340 
 341   /**  One minute, in milliseconds; convenient as a time-out value **/
 342   public static final long ONE_MINUTE = 60 * ONE_SECOND;
 343 
 344   /**  One hour, in milliseconds; convenient as a time-out value **/
 345   public static final long ONE_HOUR = 60 * ONE_MINUTE;
 346 
 347   /**  One day, in milliseconds; convenient as a time-out value **/
 348   public static final long ONE_DAY = 24 * ONE_HOUR;
 349 
 350   /**  One week, in milliseconds; convenient as a time-out value **/
 351   public static final long ONE_WEEK = 7 * ONE_DAY;
 352 
 353   /**  One year in milliseconds; convenient as a time-out value  **/
 354   // Not that it matters, but there is some variation across
 355   // standard sources about value at msec precision.
 356   // The value used is the same as in java.util.GregorianCalendar
 357   public static final long ONE_YEAR = (long)(365.2425 * ONE_DAY);
 358 
 359   /**  One century in milliseconds; convenient as a time-out value **/
 360   public static final long ONE_CENTURY = 100 * ONE_YEAR;
 361 
 362 
 363 }