samples/reentrant/src/org/apidesign/reentrant/CriticalSectionReentrantForLoop.java
author Jaroslav Tulach <jtulach@netbeans.org>
Sat, 14 Jun 2008 09:54:37 +0200
changeset 112 64308321f7bd
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 CriticalSectionReentrantForLoop<T extends Comparable<T>> implements CriticalSection<T> {
     7     private volatile 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.for
    15     public int sumBigger(Collection<T> args) {
    16         T pilotCopy = this.pilot;
    17         for (;;) {
    18             int previous = cnt.get();
    19             int own = doCriticalSection(args, pilotCopy);
    20             // if there was no parallel or reentrant change, 
    21             // apply and return. Otherwise try once more.
    22             if (cnt.compareAndSet(previous, own + previous)) {
    23                 return own;
    24             }
    25         }
    26     }
    27     // END: reentrant.merge.for
    28     
    29     private int doCriticalSection(Collection<T> args, T pilotCopy) {
    30         int own = 0;
    31         for (T cmp : args) {
    32             if (pilotCopy.compareTo(cmp) < 0) {
    33                 own++;
    34             }
    35         }
    36         return own;
    37     }
    38 
    39     public int getCount() {
    40         return cnt.get();
    41     }
    42 }