| author | Jaroslav Tulach <jtulach@netbeans.org> |
| Fri Aug 27 14:06:39 2010 +0200 | |
| changeset 365 | 0b7ec6ef8a72 |
| parent 333 | 9fd8d2574d7f |
| permissions | -rw-r--r-- |
| jtulach@71 | 1 |
/* |
| jtulach@71 | 2 |
* To change this template, choose Tools | Templates |
| jtulach@71 | 3 |
* and open the template in the editor. |
| jtulach@71 | 4 |
*/ |
| jtulach@71 | 5 |
|
| jtulach@330 | 6 |
package org.apidesign.privileged.api; |
| jtulach@71 | 7 |
|
| jtulach@71 | 8 |
import java.util.concurrent.locks.Lock; |
| jtulach@71 | 9 |
import java.util.concurrent.locks.ReentrantLock; |
| jtulach@71 | 10 |
|
| jtulach@71 | 11 |
/** |
| jtulach@71 | 12 |
* |
| jtulach@71 | 13 |
* @author Jaroslav Tulach <jaroslav.tulach@netbeans.org> |
| jtulach@71 | 14 |
*/ |
| jtulach@330 | 15 |
// BEGIN: mutex.api |
| jtulach@333 | 16 |
public final class Mutex {
|
| jtulach@71 | 17 |
Lock lock = new ReentrantLock(); |
| jtulach@71 | 18 |
|
| jtulach@71 | 19 |
public Mutex() {
|
| jtulach@71 | 20 |
} |
| jtulach@71 | 21 |
|
| jtulach@335 | 22 |
public void withLock(Runnable r) {
|
| jtulach@71 | 23 |
try {
|
| jtulach@71 | 24 |
lock.lock(); |
| jtulach@71 | 25 |
r.run(); |
| jtulach@71 | 26 |
} finally {
|
| jtulach@71 | 27 |
lock.unlock(); |
| jtulach@71 | 28 |
} |
| jtulach@71 | 29 |
} |
| jtulach@330 | 30 |
// FINISH: mutex.api |
| jtulach@71 | 31 |
|
| jtulach@330 | 32 |
// BEGIN: mutex.privileged.api |
| jtulach@71 | 33 |
public Mutex(Privileged privileged) {
|
| jtulach@71 | 34 |
if (privileged.mutex != null) {
|
| jtulach@71 | 35 |
throw new IllegalStateException(); |
| jtulach@71 | 36 |
} |
| jtulach@71 | 37 |
privileged.mutex = this; |
| jtulach@71 | 38 |
} |
| jtulach@71 | 39 |
|
| jtulach@71 | 40 |
public static final class Privileged {
|
| jtulach@71 | 41 |
private Mutex mutex; |
| jtulach@71 | 42 |
|
| jtulach@335 | 43 |
public void lock() {
|
| jtulach@71 | 44 |
mutex.lock.lock(); |
| jtulach@71 | 45 |
} |
| jtulach@71 | 46 |
|
| jtulach@335 | 47 |
public void unlock() {
|
| jtulach@71 | 48 |
mutex.lock.unlock(); |
| jtulach@71 | 49 |
} |
| jtulach@71 | 50 |
} |
| jtulach@330 | 51 |
// END: mutex.privileged.api |
| jtulach@71 | 52 |
} |