Last active
December 18, 2015 10:19
-
-
Save disolovyov/5767776 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 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