Skip to content

Instantly share code, notes, and snippets.

@disolovyov
Last active December 18, 2015 10:19
Show Gist options
  • Save disolovyov/5767776 to your computer and use it in GitHub Desktop.
Save disolovyov/5767776 to your computer and use it in GitHub Desktop.
public class Batcher<T> {
private class Batch<T> {
private final Collection<T> items = new ConcurrentLinkedQueue<>();
private final AtomicInteger permits = new AtomicInteger();
private Collection<T> getItems() {
return items;
}
private AtomicInteger getPermits() {
return permits;
}
}
private volatile Batch<T> batch;
public Batcher() {
swap();
}
public Collection<T> swap() {
Batch<T> currentBatch = batch;
batch = new Batch<>();
if (currentBatch != null) {
AtomicInteger currentPermits = currentBatch.getPermits();
for (; ; ) {
if (currentPermits.get() == 0) {
return currentBatch.getItems();
}
}
}
return null;
}
public void add(T item) {
Batch<T> currentBatch = batch;
currentBatch.getPermits().incrementAndGet();
currentBatch.getItems().add(item);
currentBatch.getPermits().decrementAndGet();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment