KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > sape > carbon > core > util > thread > Sync


1 /*
2  * The contents of this file are subject to the Sapient Public License
3  * Version 1.0 (the "License"); you may not use this file except in compliance
4  * with the License. You may obtain a copy of the License at
5  * http://carbon.sf.net/License.html.
6  *
7  * Software distributed under the License is distributed on an "AS IS" basis,
8  * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for
9  * the specific language governing rights and limitations under the License.
10  *
11  * The Original Code is The Carbon Component Framework.
12  *
13  * The Initial Developer of the Original Code is Sapient Corporation
14  *
15  * Copyright (C) 2003 Sapient Corporation. All Rights Reserved.
16  */

17
18 package org.sape.carbon.core.util.thread;
19
20 /*
21   Originally written by Doug Lea and released into the public domain.
22   This may be used for any purposes whatsoever without acknowledgment.
23   Thanks for the assistance and support of Sun Microsystems Labs,
24   and everyone contributing, testing, and using this code.
25
26   History:
27   Date Who What
28   11 Jun1998 dl Create public version
29    5 Aug1998 dl Added some convenient time constants
30 */

31
32
33 /**
34  * Main interface for locks, gates, and conditions.
35  * <p>
36  * Sync objects isolate waiting and notification for particular
37  * logical states, resource availability, events, and the like that are
38  * shared across multiple threads. Use of Syncs sometimes
39  * (but by no means always) adds flexibility and efficiency
40  * compared to the use of plain java monitor methods
41  * and locking, and are sometimes (but by no means always)
42  * simpler to program with.
43  * <p>
44  *
45  * Most Syncs are intended to be used primarily (although
46  * not exclusively) in before/after constructions such as:
47  * <pre>
48  * class X {
49  * Sync gate;
50  * // ...
51  *
52  * public void m() {
53  * try {
54  * gate.acquire(); // block until condition holds
55  * try {
56  * // ... method body
57  * }
58  * finally {
59  * gate.release()
60  * }
61  * }
62  * catch (InterruptedException ex) {
63  * // ... evasive action
64  * }
65  * }
66  *
67  * public void m2(Sync cond) { // use supplied condition
68  * try {
69  * if (cond.attempt(10)) { // try the condition for 10 ms
70  * try {
71  * // ... method body
72  * }
73  * finally {
74  * cond.release()
75  * }
76  * }
77  * }
78  * catch (InterruptedException ex) {
79  * // ... evasive action
80  * }
81  * }
82  * }
83  * </pre>
84  * Syncs may be used in somewhat tedious but more flexible replacements
85  * for built-in Java synchronized blocks. For example:
86  * <pre>
87  * class HandSynched {
88  * private double state_ = 0.0;
89  * private final Sync lock; // use lock type supplied in constructor
90  * public HandSynched(Sync l) { lock = l; }
91  *
92  * public void changeState(double d) {
93  * try {
94  * lock.acquire();
95  * try { state_ = updateFunction(d); }
96  * finally { lock.release(); }
97  * }
98  * catch(InterruptedException ex) { }
99  * }
100  *
101  * public double getState() {
102  * double d = 0.0;
103  * try {
104  * lock.acquire();
105  * try { d = accessFunction(state_); }
106  * finally { lock.release(); }
107  * }
108  * catch(InterruptedException ex){}
109  * return d;
110  * }
111  * private double updateFunction(double d) { ... }
112  * private double accessFunction(double d) { ... }
113  * }
114  * </pre>
115  * If you have a lot of such methods, and they take a common
116  * form, you can standardize this using wrappers. Some of these
117  * wrappers are standardized in LockedExecutor, but you can make others.
118  * For example:
119  * <pre>
120  * class HandSynchedV2 {
121  * private double state_ = 0.0;
122  * private final Sync lock; // use lock type supplied in constructor
123  * public HandSynchedV2(Sync l) { lock = l; }
124  *
125  * protected void runSafely(Runnable r) {
126  * try {
127  * lock.acquire();
128  * try { r.run(); }
129  * finally { lock.release(); }
130  * }
131  * catch (InterruptedException ex) { // propagate without throwing
132  * Thread.currentThread().interrupt();
133  * }
134  * }
135  *
136  * public void changeState(double d) {
137  * runSafely(new Runnable() {
138  * public void run() { state_ = updateFunction(d); }
139  * });
140  * }
141  * // ...
142  * }
143  * </pre>
144  * <p>
145  * One reason to bother with such constructions is to use deadlock-
146  * avoiding back-offs when dealing with locks involving multiple objects.
147  * For example, here is a Cell class that uses attempt to back-off
148  * and retry if two Cells are trying to swap values with each other
149  * at the same time.
150  * <pre>
151  * class Cell {
152  * long value;
153  * Sync lock = ... // some sync implementation class
154  * void swapValue(Cell other) {
155  * for (;;) {
156  * try {
157  * lock.acquire();
158  * try {
159  * if (other.lock.attempt(100)) {
160  * try {
161  * long t = value;
162  * value = other.value;
163  * other.value = t;
164  * return;
165  * }
166  * finally { other.lock.release(); }
167  * }
168  * }
169  * finally { lock.release(); }
170  * }
171  * catch (InterruptedException ex) { return; }
172  * }
173  * }
174  * }
175  *</pre>
176  * <p>
177  * Here is an even fancier version, that uses lock re-ordering
178  * upon conflict:
179  * <pre>
180  * class Cell {
181  * long value;
182  * Sync lock = ...;
183  * private static boolean trySwap(Cell a, Cell b) {
184  * a.lock.acquire();
185  * try {
186  * if (!b.lock.attempt(0))
187  * return false;
188  * try {
189  * long t = a.value;
190  * a.value = b.value;
191  * b.value = t;
192  * return true;
193  * }
194  * finally { other.lock.release(); }
195  * }
196  * finally { lock.release(); }
197  * return false;
198  * }
199  *
200  * void swapValue(Cell other) {
201  * try {
202  * while (!trySwap(this, other) &&
203  * !tryswap(other, this))
204  * Thread.sleep(1);
205  * }
206  * catch (InterruptedException ex) { return; }
207  * }
208  *}
209  *</pre>
210  * <p>
211  * Interruptions are in general handled as early as possible.
212  * Normally, InterruptionExceptions are thrown
213  * in acquire and attempt(msec) if interruption
214  * is detected upon entry to the method, as well as in any
215  * later context surrounding waits.
216  * However, interruption status is ignored in release();
217  * <p>
218  * Timed versions of attempt report failure via return value.
219  * If so desired, you can transform such constructions to use exception
220  * throws via
221  * <pre>
222  * if (!c.attempt(timeval)) throw new TimeoutException(timeval);
223  * </pre>
224  * <p>
225  * The TimoutSync wrapper class can be used to automate such usages.
226  * <p>
227  * All time values are expressed in milliseconds as longs, which have a maximum
228  * value of Long.MAX_VALUE, or almost 300,000 centuries. It is not
229  * known whether JVMs actually deal correctly with such extreme values.
230  * For convenience, some useful time values are defined as static constants.
231  * <p>
232  * All implementations of the three Sync methods guarantee to
233  * somehow employ Java <code>synchronized</code> methods or blocks,
234  * and so entail the memory operations described in JLS
235  * chapter 17 which ensure that variables are loaded and flushed
236  * within before/after constructions.
237  * <p>
238  * Syncs may also be used in spinlock constructions. Although
239  * it is normally best to just use acquire(), various forms
240  * of busy waits can be implemented. For a simple example
241  * (but one that would probably never be preferable to using acquire()):
242  * <pre>
243  * class X {
244  * Sync lock = ...
245  * void spinUntilAcquired() throws InterruptedException {
246  * // Two phase.
247  * // First spin without pausing.
248  * int purespins = 10;
249  * for (int i = 0; i < purespins; ++i) {
250  * if (lock.attempt(0))
251  * return true;
252  * }
253  * // Second phase - use timed waits
254  * long waitTime = 1; // 1 millisecond
255  * for (;;) {
256  * if (lock.attempt(waitTime))
257  * return true;
258  * else
259  * waitTime = waitTime * 3 / 2 + 1; // increase 50%
260  * }
261  * }
262  * }
263  * </pre>
264  * <p>
265  * In addition pure synchronization control, Syncs
266  * may be useful in any context requiring before/after methods.
267  * For example, you can use an ObservableSync
268  * (perhaps as part of a LayeredSync) in order to obtain callbacks
269  * before and after each method invocation for a given class.
270  * <p>
271
272  * <p>[<a HREF="http://gee.cs.oswego.edu/dl/classes/EDU/oswego/cs/dl/util/concurrent/intro.html"> Introduction to this package. </a>]
273  *
274  * @since carbon 2.0
275  * @author Doug Lea
276  * @version $Revision: 1.3 $($Author: dvoet $ / $Date: 2003/05/05 21:21:24 $)
277  **/

278 public interface Sync {
279
280   /**
281    * Wait (possibly forever) until successful passage.
282    * Fail only upon interuption. Interruptions always result in
283    * `clean' failures. On failure, you can be sure that it has not
284    * been acquired, and that no
285    * corresponding release should be performed. Conversely,
286    * a normal return guarantees that the acquire was successful.
287   **/

288
289   public void acquire() throws InterruptedException JavaDoc;
290
291   /**
292    * Wait at most msecs to pass; report whether passed.
293    * <p>
294    * The method has best-effort semantics:
295    * The msecs bound cannot
296    * be guaranteed to be a precise upper bound on wait time in Java.
297    * Implementations generally can only attempt to return as soon as possible
298    * after the specified bound. Also, timers in Java do not stop during garbage
299    * collection, so timeouts can occur just because a GC intervened.
300    * So, msecs arguments should be used in
301    * a coarse-grained manner. Further,
302    * implementations cannot always guarantee that this method
303    * will return at all without blocking indefinitely when used in
304    * unintended ways. For example, deadlocks may be encountered
305    * when called in an unintended context.
306    * <p>
307    * @param msecs the number of milleseconds to wait.
308    * An argument less than or equal to zero means not to wait at all.
309    * However, this may still require
310    * access to a synchronization lock, which can impose unbounded
311    * delay if there is a lot of contention among threads.
312    * @return true if acquired
313   **/

314
315   public boolean attempt(long msecs) throws InterruptedException JavaDoc;
316
317   /**
318    * Potentially enable others to pass.
319    * <p>
320    * Because release does not raise exceptions,
321    * it can be used in `finally' clauses without requiring extra
322    * embedded try/catch blocks. But keep in mind that
323    * as with any java method, implementations may
324    * still throw unchecked exceptions such as Error or NullPointerException
325    * when faced with uncontinuable errors. However, these should normally
326    * only be caught by higher-level error handlers.
327   **/

328
329   public void release();
330
331   /** One second, in milliseconds; convenient as a time-out value **/
332   public static final long ONE_SECOND = 1000;
333
334   /** One minute, in milliseconds; convenient as a time-out value **/
335   public static final long ONE_MINUTE = 60 * ONE_SECOND;
336
337   /** One hour, in milliseconds; convenient as a time-out value **/
338   public static final long ONE_HOUR = 60 * ONE_MINUTE;
339
340   /** One day, in milliseconds; convenient as a time-out value **/
341   public static final long ONE_DAY = 24 * ONE_HOUR;
342
343   /** One week, in milliseconds; convenient as a time-out value **/
344   public static final long ONE_WEEK = 7 * ONE_DAY;
345
346   /** One year in milliseconds; convenient as a time-out value **/
347   // Not that it matters, but there is some variation across
348
// standard sources about value at msec precision.
349
// The value used is the same as in java.util.GregorianCalendar
350
public static final long ONE_YEAR = (long)(365.2425 * ONE_DAY);
351
352   /** One century in milliseconds; convenient as a time-out value **/
353   public static final long ONE_CENTURY = 100 * ONE_YEAR;
354
355
356 }
357
358
359
Popular Tags