1 4 package com.tc.util.sequence; 5 6 import EDU.oswego.cs.dl.util.concurrent.FutureResult; 7 import EDU.oswego.cs.dl.util.concurrent.LinkedQueue; 8 import junit.framework.TestCase; 9 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 BatchSequenceProvider { 57 public volatile int size = -1; 58 public final LinkedQueue queue = new LinkedQueue(); 59 60 public void requestBatch(BatchSequenceReceiver theProvider, int theSize) { 61 this.size = theSize; 62 try { 63 queue.put(theProvider); 64 } catch (InterruptedException e) { 65 throw new AssertionError (e); 66 } 67 } 68 69 public boolean isEmpty() { 70 return queue.isEmpty(); 71 } 72 73 public Object poll(long l) throws InterruptedException { 74 return queue.poll(l); 75 } 76 77 public Object take() throws InterruptedException { 78 return queue.take(); 79 } 80 81 public void clear() throws InterruptedException { 82 this.size = -1; 83 while(!queue.isEmpty()) { 84 queue.take(); 85 } 86 } 87 } 88 } 89 | Popular Tags |