01: /*
02: File: LockedExecutor.java
03:
04: Originally written by Doug Lea and released into the public domain.
05: This may be used for any purposes whatsoever without acknowledgment.
06: Thanks for the assistance and support of Sun Microsystems Labs,
07: and everyone contributing, testing, and using this code.
08:
09: History:
10: Date Who What
11: 21Jun1998 dl Create public version
12: */
13:
14: package EDU.oswego.cs.dl.util.concurrent;
15:
16: /**
17: * An implementation of Executor that
18: * invokes the run method of the supplied command within
19: * a synchronization lock and then returns.
20: *
21: * <p>[<a href="http://gee.cs.oswego.edu/dl/classes/EDU/oswego/cs/dl/util/concurrent/intro.html"> Introduction to this package. </a>]
22: **/
23: public class LockedExecutor implements Executor {
24:
25: /** The mutex **/
26: protected final Sync mutex_;
27:
28: /**
29: * Create a new LockedExecutor that relies on the given mutual
30: * exclusion lock.
31: * @param mutex Any mutual exclusion lock.
32: * Standard usage is to supply an instance of <code>Mutex</code>,
33: * but, for example, a Semaphore initialized to 1 also works.
34: * On the other hand, many other Sync implementations would not
35: * work here, so some care is required to supply a sensible
36: * synchronization object.
37: **/
38:
39: public LockedExecutor(Sync mutex) {
40: mutex_ = mutex;
41: }
42:
43: /**
44: * Execute the given command directly in the current thread,
45: * within the supplied lock.
46: **/
47: public void execute(Runnable command) throws InterruptedException {
48: mutex_.acquire();
49: try {
50: command.run();
51: } finally {
52: mutex_.release();
53: }
54: }
55:
56: }
|