samples/privilegedcreator/src/org/apidesign/privileged/api/Mutex.java
author Jaroslav Tulach <jaroslav.tulach@apidesign.org>
Thu, 30 Oct 2014 21:30:10 +0100
changeset 409 40cabcdcd2be
parent 333 9fd8d2574d7f
permissions -rw-r--r--
Updating to NBMs from NetBeans 8.0.1 as some of them are required to run on JDK8
     1 /*
     2  * To change this template, choose Tools | Templates
     3  * and open the template in the editor.
     4  */
     5 
     6 package org.apidesign.privileged.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 // BEGIN: mutex.api
    16 public final class Mutex {
    17     Lock lock = new ReentrantLock();
    18     
    19     public Mutex() {
    20     }
    21     
    22     public void withLock(Runnable r) {
    23         try {
    24             lock.lock();
    25             r.run();
    26         } finally {
    27             lock.unlock();
    28         }
    29     }
    30 // FINISH: mutex.api
    31 
    32 // BEGIN: mutex.privileged.api
    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 lock() {
    44             mutex.lock.lock();
    45         }
    46         
    47         public void unlock() {
    48             mutex.lock.unlock();
    49         }
    50     }
    51 // END: mutex.privileged.api
    52 }