01: /*
02: * All content copyright (c) 2003-2006 Terracotta, Inc., except as may otherwise be noted in a separate copyright notice. All rights reserved.
03: */
04: package com.tc.util.sequence;
05:
06: import EDU.oswego.cs.dl.util.concurrent.FutureResult;
07: import EDU.oswego.cs.dl.util.concurrent.LinkedQueue;
08: import junit.framework.TestCase;
09:
10: public class BatchSequenceTest extends TestCase {
11:
12: public void test() throws Exception {
13: TestRemoteBatchIDProvider remote = new TestRemoteBatchIDProvider();
14: final BatchSequence sequence = new BatchSequence(remote, 5);
15: final LinkedQueue longs = new LinkedQueue();
16:
17: final FutureResult barrier = new FutureResult();
18:
19: Thread t = new Thread("BatchIDProviderTestThread") {
20: public void run() {
21: barrier.set(new Object());
22: try {
23: longs.put(new Long(sequence.next()));
24: } catch (InterruptedException e) {
25: e.printStackTrace();
26: throw new AssertionError(e);
27: }
28: }
29: };
30:
31: t.start();
32: barrier.get();
33: assertTrue(longs.poll(2000) == null);
34: assertTrue(remote.take() == sequence);
35: assertTrue(remote.size == 5);
36:
37: remote.clear();
38: sequence.setNextBatch(0, 5);
39: assertTrue(remote.take() != null);
40: remote.clear();
41: sequence.setNextBatch(5, 10);
42:
43: assertTrue(((Long) longs.take()).longValue() == 0);
44: assertTrue(sequence.next() == 1);
45: assertTrue(sequence.next() == 2);
46: assertTrue(sequence.next() == 3);
47: assertTrue(sequence.next() == 4);
48: assertTrue(remote.isEmpty());
49: assertTrue(sequence.next() == 5);
50: assertFalse(remote.isEmpty());
51: assertTrue(remote.take() != null);
52: sequence.setNextBatch(10, 15);
53: assertTrue(sequence.next() == 6);
54: }
55:
56: private static class TestRemoteBatchIDProvider implements
57: BatchSequenceProvider {
58: public volatile int size = -1;
59: public final LinkedQueue queue = new LinkedQueue();
60:
61: public void requestBatch(BatchSequenceReceiver theProvider,
62: int theSize) {
63: this .size = theSize;
64: try {
65: queue.put(theProvider);
66: } catch (InterruptedException e) {
67: throw new AssertionError(e);
68: }
69: }
70:
71: public boolean isEmpty() {
72: return queue.isEmpty();
73: }
74:
75: public Object poll(long l) throws InterruptedException {
76: return queue.poll(l);
77: }
78:
79: public Object take() throws InterruptedException {
80: return queue.take();
81: }
82:
83: public void clear() throws InterruptedException {
84: this .size = -1;
85: while (!queue.isEmpty()) {
86: queue.take();
87: }
88: }
89: }
90: }
|