Skip to content

Instantly share code, notes, and snippets.

@jleedev
Last active February 11, 2017 15:17
Show Gist options
  • Save jleedev/03b61ba7066c5c4051770245c03c6e06 to your computer and use it in GitHub Desktop.
Save jleedev/03b61ba7066c5c4051770245c03c6e06 to your computer and use it in GitHub Desktop.
java producer consumer
package com.example;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.*;
public class Main {
static void run(int inputSize, int batchSize) throws Exception {
ExecutorService executor = Executors.newCachedThreadPool();
BlockingQueue<Integer> q = new LinkedBlockingQueue<>(2 * batchSize);
Future<Void> p = executor.submit(() -> {
for (int i = 0; i < inputSize; i++) {
q.put(i);
}
return null;
});
while (!p.isDone() || !q.isEmpty()) {
executor.submit(() -> {
List<Integer> lst = new ArrayList<>();
q.drainTo(lst, batchSize);
System.out.println(lst);
return null;
}).get();
}
executor.shutdown();
}
public static void main(String[] args) throws Exception {
run(18, 5);
run(0, 2);
run(10, 5);
run(10, 4);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment