KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > tc > util > sequence > BatchSequence


1 /**
2  * All content copyright (c) 2003-2006 Terracotta, Inc., except as may otherwise be noted in a separate copyright notice. All rights reserved.
3  */

4 package com.tc.util.sequence;
5
6 import com.tc.exception.TCRuntimeException;
7 import com.tc.util.sequence.BatchSequenceProvider;
8
9 /**
10  * This Sequence deals with batches. It keeps a next batch around to avoid
11  * pauses and always requests a new next batch as soon as the old next batch is
12  * promoted to current batch
13  *
14  * @author steve, orion
15  */

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     // This should only happen the first time
39
while (!current.hasNext() && !nextBatch.hasNext()) {
40       if (!requestInProgress) requestNextBatch();
41       try {
42         this.wait();
43       } catch (InterruptedException JavaDoc ie) {
44         throw new TCRuntimeException(ie);
45       }
46     }
47
48     // This is the more normal case
49
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   // The currentBatch is not considered here as we want to greedily get the next set even if the
68
// current set has some available.
69
public synchronized boolean hasNext() {
70     return nextBatch.hasNext();
71   }
72 }
Popular Tags