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
     1 package org.apidesign.reentrant;
     2 
     3 import java.nio.channels.NonReadableChannelException;
     4 import java.util.Collection;
     5 import java.util.concurrent.locks.Lock;
     6 
     7 public class CriticalSectionSynchronizedWithNonReentrantLock<T extends Comparable<T>> implements CriticalSection<T> {
     8     private T pilot;
     9     private int cnt;
    10     
    11     public void assignPilot(T pilot) {
    12         lock.lock();
    13         try {
    14             this.pilot = pilot;
    15         } finally {
    16             lock.unlock();
    17         }
    18     }
    19 
    20     // BEGIN: reentrant.nonreentrant.lock
    21     private Lock lock = new NonReentrantLock();
    22     public int sumBigger(Collection<T> args) {
    23         lock.lock();
    24         try {
    25             return doCriticalSection(args);
    26         } finally {
    27             lock.unlock();
    28         }
    29     }
    30     // END: reentrant.nonreentrant.lock
    31     
    32     private int doCriticalSection(Collection<T> args) {
    33         for (T cmp : args) {
    34             if (pilot.compareTo(cmp) < 0) {
    35                 cnt++;
    36             }
    37         }
    38         return cnt;
    39     }
    40     
    41     public int getCount() {
    42         lock.lock();
    43         try {
    44             return cnt;
    45         } finally {
    46             lock.unlock();
    47         }
    48     }
    49 }