samples/reentrant/src/org/apidesign/reentrant/CriticalSectionReentrantImmutable.java
1 package org.apidesign.reentrant;
3 import java.util.Collection;
4 import java.util.concurrent.atomic.AtomicInteger;
6 public class CriticalSectionReentrantImmutable<T extends Comparable<T>> implements CriticalSection<T> {
7 private ImmutableData<T> data = new ImmutableData<T>();
9 public void assignPilot(T pilot) {
10 data = data.newPilot(pilot);
13 // BEGIN: reentrant.merge.immutable
14 public int sumBigger(Collection<T> args) {
16 ImmutableData<T> previous;
21 ImmutableData<T> now = doCriticalSection(args, previous, ret);
24 // if there was no parallel or reentrant change,
25 // apply and return. Otherwise try once more.
26 if (previous == this.data) {
33 // END: reentrant.merge.immutable
35 private ImmutableData<T> doCriticalSection(Collection<T> args, ImmutableData<T> data, int[] result) {
38 if (data.pilot.compareTo(cmp) < 0) {
42 return data.newCnt(data.cnt + result[0]);
45 public int getCount() {
49 private static final class ImmutableData<T> {
53 public ImmutableData() {
57 private ImmutableData(T pilot, int cnt) {
62 public ImmutableData<T> newPilot(T pilot) {
63 return new ImmutableData(pilot, this.cnt);
65 public ImmutableData<T> newCnt(int cnt) {
66 return new ImmutableData(this.pilot, cnt);