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
jtulach@112
     1
package org.apidesign.reentrant;
jtulach@112
     2
jtulach@112
     3
import java.util.Collection;
jtulach@112
     4
import java.util.concurrent.atomic.AtomicInteger;
jtulach@112
     5
jtulach@112
     6
public class CriticalSectionReentrantForLoop<T extends Comparable<T>> implements CriticalSection<T> {
jtulach@112
     7
    private volatile T pilot;
jtulach@112
     8
    private AtomicInteger cnt = new AtomicInteger();
jtulach@112
     9
    
jtulach@112
    10
    public void assignPilot(T pilot) {
jtulach@112
    11
        this.pilot = pilot;
jtulach@112
    12
    }
jtulach@112
    13
jtulach@112
    14
    // BEGIN: reentrant.merge.for
jtulach@112
    15
    public int sumBigger(Collection<T> args) {
jtulach@112
    16
        T pilotCopy = this.pilot;
jtulach@112
    17
        for (;;) {
jtulach@112
    18
            int previous = cnt.get();
jtulach@112
    19
            int own = doCriticalSection(args, pilotCopy);
jtulach@112
    20
            // if there was no parallel or reentrant change, 
jtulach@112
    21
            // apply and return. Otherwise try once more.
jtulach@112
    22
            if (cnt.compareAndSet(previous, own + previous)) {
jtulach@112
    23
                return own;
jtulach@112
    24
            }
jtulach@112
    25
        }
jtulach@112
    26
    }
jtulach@112
    27
    // END: reentrant.merge.for
jtulach@112
    28
    
jtulach@112
    29
    private int doCriticalSection(Collection<T> args, T pilotCopy) {
jtulach@112
    30
        int own = 0;
jtulach@112
    31
        for (T cmp : args) {
jtulach@112
    32
            if (pilotCopy.compareTo(cmp) < 0) {
jtulach@112
    33
                own++;
jtulach@112
    34
            }
jtulach@112
    35
        }
jtulach@112
    36
        return own;
jtulach@112
    37
    }
jtulach@112
    38
jtulach@112
    39
    public int getCount() {
jtulach@112
    40
        return cnt.get();
jtulach@112
    41
    }
jtulach@112
    42
}