1 4 package com.tc.util.sequence; 5 6 import com.tc.exception.TCRuntimeException; 7 import com.tc.util.sequence.BatchSequenceProvider; 8 9 16 public final class BatchSequence implements BatchSequenceReceiver, Sequence { 17 18 private static final SequenceBatch NULL_SEQUENCE_BATCH = new SequenceBatch(0, 0); 19 20 private SequenceBatch current = NULL_SEQUENCE_BATCH; 21 private SequenceBatch nextBatch = NULL_SEQUENCE_BATCH; 22 private boolean requestInProgress; 23 private final BatchSequenceProvider remoteProvider; 24 private final int batchSize; 25 26 public BatchSequence(BatchSequenceProvider sequenceProvider, int batchSize) { 27 this.remoteProvider = sequenceProvider; 28 this.batchSize = batchSize; 29 } 30 31 public synchronized long next() { 32 requestMoreIDsIfNecessary(); 33 return current.next(); 34 } 35 36 private void requestMoreIDsIfNecessary() { 37 38 while (!current.hasNext() && !nextBatch.hasNext()) { 40 if (!requestInProgress) requestNextBatch(); 41 try { 42 this.wait(); 43 } catch (InterruptedException ie) { 44 throw new TCRuntimeException(ie); 45 } 46 } 47 48 if (!current.hasNext()) { 50 this.current = nextBatch; 51 this.nextBatch = NULL_SEQUENCE_BATCH; 52 requestNextBatch(); 53 } 54 } 55 56 private void requestNextBatch() { 57 remoteProvider.requestBatch(this, batchSize); 58 this.requestInProgress = true; 59 } 60 61 public synchronized void setNextBatch(long start, long end) { 62 this.nextBatch = new SequenceBatch(start, end); 63 this.requestInProgress = false; 64 this.notifyAll(); 65 } 66 67 public synchronized boolean hasNext() { 70 return nextBatch.hasNext(); 71 } 72 } | Popular Tags |