samples/reentrant/src/org/apidesign/reentrant/CriticalSectionReentrant.java
author Jaroslav Tulach <jtulach@netbeans.org>
Sat, 14 Jun 2008 09:54:37 +0200
changeset 112 64308321f7bd
parent 111 3905a2e66b9b
child 115 2c1b90108e02
permissions -rw-r--r--
Reentrant access examples rewritten to make a bit more sence
     1 package org.apidesign.reentrant;
     2 
     3 import java.util.Collection;
     4 import java.util.concurrent.atomic.AtomicInteger;
     5 
     6 public class CriticalSectionReentrant<T extends Comparable<T>> implements CriticalSection<T> {
     7     private T pilot;
     8     private AtomicInteger cnt = new AtomicInteger();
     9     
    10     public void assignPilot(T pilot) {
    11         this.pilot = pilot;
    12     }
    13 
    14     public int sumBigger(Collection<T> args) {
    15         T pilotCopy = this.pilot;
    16         int own = doCriticalSection(args, pilotCopy);
    17         // now merge with global state
    18         cnt.addAndGet(own);
    19         return own;
    20     }
    21     
    22     private int doCriticalSection(Collection<T> args, T pilotCopy) {
    23         int own = 0;
    24         for (T cmp : args) {
    25             if (pilotCopy.compareTo(cmp) < 0) {
    26                 own++;
    27             }
    28         }
    29         return own;
    30     }
    31 
    32     public int getCount() {
    33         return cnt.get();
    34     }
    35 }