samples/reentrant/src/org/apidesign/reentrant/CriticalSectionReentrant.java
author Jaroslav Tulach <jtulach@netbeans.org>
Sat, 14 Jun 2008 09:54:41 +0200
changeset 115 2c1b90108e02
parent 112 64308321f7bd
child 205 6ad6f4162691
permissions -rw-r--r--
This code needs to be included in the PDF
     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     // BEGIN: reentrant.merge.int
    15     public int sumBigger(Collection<T> args) {
    16         T pilotCopy = this.pilot;
    17         int own = doCriticalSection(args, pilotCopy);
    18         // now merge with global state
    19         cnt.addAndGet(own);
    20         return own;
    21     }
    22     // END: reentrant.merge.int
    23     
    24     private int doCriticalSection(Collection<T> args, T pilotCopy) {
    25         int own = 0;
    26         for (T cmp : args) {
    27             if (pilotCopy.compareTo(cmp) < 0) {
    28                 own++;
    29             }
    30         }
    31         return own;
    32     }
    33 
    34     public int getCount() {
    35         return cnt.get();
    36     }
    37 }