samples/reentrant/src/org/apidesign/reentrant/CriticalSectionSynchronizedWithNonReentrantLock.java
author Jaroslav Tulach <jtulach@netbeans.org>
Sat, 14 Jun 2008 09:54:37 +0200
changeset 112 64308321f7bd
parent 111 3905a2e66b9b
permissions -rw-r--r--
Reentrant access examples rewritten to make a bit more sence
jtulach@111
     1
package org.apidesign.reentrant;
jtulach@111
     2
jtulach@111
     3
import java.nio.channels.NonReadableChannelException;
jtulach@111
     4
import java.util.Collection;
jtulach@111
     5
import java.util.concurrent.locks.Lock;
jtulach@111
     6
jtulach@111
     7
public class CriticalSectionSynchronizedWithNonReentrantLock<T extends Comparable<T>> implements CriticalSection<T> {
jtulach@111
     8
    private T pilot;
jtulach@111
     9
    private int cnt;
jtulach@111
    10
    
jtulach@111
    11
    public void assignPilot(T pilot) {
jtulach@111
    12
        lock.lock();
jtulach@111
    13
        try {
jtulach@111
    14
            this.pilot = pilot;
jtulach@111
    15
        } finally {
jtulach@111
    16
            lock.unlock();
jtulach@111
    17
        }
jtulach@111
    18
    }
jtulach@111
    19
jtulach@112
    20
    // BEGIN: reentrant.nonreentrant.lock
jtulach@112
    21
    private Lock lock = new NonReentrantLock();
jtulach@111
    22
    public int sumBigger(Collection<T> args) {
jtulach@111
    23
        lock.lock();
jtulach@111
    24
        try {
jtulach@112
    25
            return doCriticalSection(args);
jtulach@111
    26
        } finally {
jtulach@111
    27
            lock.unlock();
jtulach@111
    28
        }
jtulach@111
    29
    }
jtulach@112
    30
    // END: reentrant.nonreentrant.lock
jtulach@112
    31
    
jtulach@112
    32
    private int doCriticalSection(Collection<T> args) {
jtulach@112
    33
        for (T cmp : args) {
jtulach@112
    34
            if (pilot.compareTo(cmp) < 0) {
jtulach@112
    35
                cnt++;
jtulach@112
    36
            }
jtulach@112
    37
        }
jtulach@112
    38
        return cnt;
jtulach@112
    39
    }
jtulach@111
    40
    
jtulach@111
    41
    public int getCount() {
jtulach@111
    42
        lock.lock();
jtulach@111
    43
        try {
jtulach@111
    44
            return cnt;
jtulach@111
    45
        } finally {
jtulach@111
    46
            lock.unlock();
jtulach@111
    47
        }
jtulach@111
    48
    }
jtulach@111
    49
}