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 if (Boolean.getBoolean("no.failures")) return;
46 final CriticalSection<Integer> cs = create();
50 class ChangePilotTo15 implements Runnable {
51 // BEGIN: reentrant.forbidden.call
52 // if this runnable is called from inside the critical section,
53 // and the locks are non-reentrant then it throws an exception
57 // END: reentrant.forbidden.call
60 List<Integer> ints = new MyCollection(new ChangePilotTo15(), 3);
70 int cnt = cs.sumBigger(ints);
72 assertEquals("11, 12, 18, 13 are bigger than 10", 4, cnt);
74 assertEquals("Global count is sum of ints(e.g. 4) plus result of testFor15(e.g. 1)", 5, cs.getCount());
77 class MyCollection extends ArrayList<Integer> {
78 private Runnable callback;
79 private final int callbackBeforeIndex;
81 public MyCollection(Runnable callback, int callbackAtIndex) {
82 this.callback = callback;
83 this.callbackBeforeIndex = callbackAtIndex;
87 public Iterator<Integer> iterator() {
88 final Iterator<Integer> delegate = super.iterator();
89 class It implements Iterator<Integer> {
92 public boolean hasNext() {
93 return delegate.hasNext();
96 public Integer next() {
97 if (index++ == callbackBeforeIndex) {
98 if (callback != null) {
101 if (reentrantJustOnce()) {
106 return delegate.next();
109 public void remove() {