Created
December 31, 2011 15:04
-
-
Save mikeb01/1544238 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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