samples/privilegedcreator/src/api/Mutex.java
author Jaroslav Tulach <jtulach@netbeans.org>
Sat, 14 Jun 2008 09:53:28 +0200
changeset 71 a9bd40166b60
permissions -rw-r--r--
Fixed "Give creator more rights"
     1 /*
     2  * To change this template, choose Tools | Templates
     3  * and open the template in the editor.
     4  */
     5 
     6 package api;
     7 
     8 import java.util.concurrent.locks.Lock;
     9 import java.util.concurrent.locks.ReentrantLock;
    10 
    11 /**
    12  *
    13  * @author Jaroslav Tulach <jaroslav.tulach@netbeans.org>
    14  */
    15 public class Mutex {
    16     Lock lock = new ReentrantLock();
    17     
    18     public Mutex() {
    19     }
    20 
    21     
    22     public void readAccess(Runnable r) {
    23         try {
    24             lock.lock();
    25             r.run();
    26         } finally {
    27             lock.unlock();
    28         }
    29     }
    30     
    31 
    32     
    33     public Mutex(Privileged privileged) {
    34         if (privileged.mutex != null) {
    35             throw new IllegalStateException();
    36         }
    37         privileged.mutex = this;
    38     }
    39     
    40     public static final class Privileged {
    41         private Mutex mutex;
    42         
    43         public void enterReadAccess() {
    44             mutex.lock.lock();
    45         }
    46         
    47         public void exitReadAccess() {
    48             mutex.lock.unlock();
    49         }
    50     }
    51 }