samples/privilegedcreator/src/org/apidesign/privileged/api/Mutex.java
author Jaroslav Tulach <jtulach@netbeans.org>
Mon, 25 May 2009 18:27:02 +0200
changeset 330 be82436a7a8b
parent 71 samples/privilegedcreator/src/api/Mutex.java@a9bd40166b60
child 333 9fd8d2574d7f
permissions -rw-r--r--
More code snippets for the mutex example
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@71
    16
public class Mutex {
jtulach@71
    17
    Lock lock = new ReentrantLock();
jtulach@71
    18
    
jtulach@71
    19
    public Mutex() {
jtulach@71
    20
    }
jtulach@71
    21
    
jtulach@71
    22
    public void readAccess(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@71
    43
        public void enterReadAccess() {
jtulach@71
    44
            mutex.lock.lock();
jtulach@71
    45
        }
jtulach@71
    46
        
jtulach@71
    47
        public void exitReadAccess() {
jtulach@71
    48
            mutex.lock.unlock();
jtulach@71
    49
        }
jtulach@71
    50
    }
jtulach@330
    51
// END: mutex.privileged.api
jtulach@71
    52
}