samples/reentrant/src/org/apidesign/reentrant/CriticalSectionSynchronizedWithNonReentrantLock.java
author Jaroslav Tulach <jtulach@netbeans.org>
Sat, 14 Jun 2008 09:54:36 +0200
changeset 111 3905a2e66b9b
child 112 64308321f7bd
permissions -rw-r--r--
Sample code with various attempts to fight with reentrant code
     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     private Lock lock = new NonReentrantLock();
    11     
    12     public void assignPilot(T pilot) {
    13         lock.lock();
    14         try {
    15             this.pilot = pilot;
    16         } finally {
    17             lock.unlock();
    18         }
    19     }
    20 
    21     public int sumBigger(Collection<T> args) {
    22         lock.lock();
    23         try {
    24             for (T cmp : args) {
    25                 if (pilot.compareTo(cmp) < 0) {
    26                     cnt++;
    27                 }
    28             }
    29             return cnt;
    30         } finally {
    31             lock.unlock();
    32         }
    33     }
    34     
    35     public int getCount() {
    36         lock.lock();
    37         try {
    38             return cnt;
    39         } finally {
    40             lock.unlock();
    41         }
    42     }
    43 }