Skip to content

Instantly share code, notes, and snippets.

@mikeb01
Created December 31, 2011 15:04
Show Gist options
  • Save mikeb01/1544238 to your computer and use it in GitHub Desktop.
Save mikeb01/1544238 to your computer and use it in GitHub Desktop.
public void serialisePublishing(final long sequence,
final Sequence cursor,
final int batchSize) {
// Guard condition, limit the number of pending publications
int counter = RETRIES;
while (sequence - cursor.get() > pendingPublication.length()) {
if (--counter == 0) {
Thread.yield();
counter = RETRIES;
}
}
// Transition from unpublished -> pending
long expectedSequence = sequence - batchSize;
for (long pendingSequence = expectedSequence + 1; pendingSequence <= sequence; pendingSequence++) {
pendingPublication.set((int) pendingSequence & pendingMask, pendingSequence);
}
// Optimisation, if the cursor is not at the expected
// value there is no point joining the race.
long cursorSequence = cursor.get();
if (cursorSequence >= sequence) {
return;
}
expectedSequence = Math.max(expectedSequence, cursorSequence);
// Transition pending -> published
long nextSequence = expectedSequence + 1;
while (cursor.compareAndSet(expectedSequence, nextSequence)) {
expectedSequence = nextSequence;
nextSequence++;
if (pendingPublication.get((int) nextSequence & pendingMask) != nextSequence) {
break;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment