1 package org.apidesign.reentrant;
3 import java.util.ArrayList;
4 import java.util.Iterator;
7 import static org.junit.Assert.*;
9 public abstract class CriticalSectionBase {
10 protected abstract CriticalSection<Integer> create();
11 protected boolean reentrantJustOnce() {
15 // BEGIN: reentrant.ok.call
17 public void testCriticalSectionWith15() {
18 final CriticalSection<Integer> cs = create();
21 // END: reentrant.ok.call
23 final void testFor15(CriticalSection<Integer> cs) {
26 List<Integer> ints = new ArrayList<Integer>();
36 int cnt = cs.sumBigger(ints);
38 assertEquals("18 is bigger than 15", 1, cnt);
43 public void teaseCriticalSectionWithReentrantCalls() {
44 final CriticalSection<Integer> cs = create();
48 class ChangePilotTo15 implements Runnable {
49 // BEGIN: reentrant.forbidden.call
50 // if this runnable is called from inside the critical section,
51 // and the locks are non-reentrant then it throws an exception
55 // END: reentrant.forbidden.call
58 List<Integer> ints = new MyCollection(new ChangePilotTo15(), 3);
68 int cnt = cs.sumBigger(ints);
70 assertEquals("11, 12, 18, 13 are bigger than 10", 4, cnt);
72 assertEquals("Global count is sum of ints(e.g. 4) plus result of testFor15(e.g. 1)", 5, cs.getCount());
75 class MyCollection extends ArrayList<Integer> {
76 private Runnable callback;
77 private final int callbackBeforeIndex;
79 public MyCollection(Runnable callback, int callbackAtIndex) {
80 this.callback = callback;
81 this.callbackBeforeIndex = callbackAtIndex;
85 public Iterator<Integer> iterator() {
86 final Iterator<Integer> delegate = super.iterator();
87 class It implements Iterator<Integer> {
90 public boolean hasNext() {
91 return delegate.hasNext();
94 public Integer next() {
95 if (index++ == callbackBeforeIndex) {
96 if (callback != null) {
99 if (reentrantJustOnce()) {
104 return delegate.next();
107 public void remove() {