samples/reentrant/src/org/apidesign/reentrant/CriticalSectionReentrant.java
author Jaroslav Tulach <jtulach@netbeans.org>
Sat, 14 Jun 2008 10:04:53 +0200
changeset 210 acf2c31e22d4
parent 209 1c999569643b
permissions -rw-r--r--
Merge: Geertjan's changes to the end of the chapter
     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     
     9     public void assignPilot(T pilot) {
    10         this.pilot = pilot;
    11     }
    12 
    13     // BEGIN: reentrant.merge.int
    14     private AtomicInteger cnt = new AtomicInteger();
    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 }