Created
October 15, 2020 07:09
-
-
Save saswata-dutta/9d3b6e8a003ac7789607b62769373dd2 to your computer and use it in GitHub Desktop.
Java batched executor sample
This file contains hidden or 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
package org.saswata; | |
import java.util.ArrayList; | |
import java.util.Arrays; | |
import java.util.HashSet; | |
import java.util.concurrent.ExecutorService; | |
import java.util.concurrent.Executors; | |
import java.util.concurrent.TimeUnit; | |
public class Test { | |
public static void main(String[] args) { | |
final int BATCH = 10; | |
ArrayList<Integer> accumulator = new ArrayList<>(); | |
ExecutorService executorService = Executors.newFixedThreadPool(3); | |
for (int i = 0; i < BATCH * 10; i++) { | |
accumulator.add(i); | |
if (accumulator.size() >= BATCH) { | |
final Object[] temp = accumulator.toArray(); | |
executorService.submit(() -> run(temp)); | |
accumulator.clear(); | |
} | |
} | |
executorService.shutdown(); | |
try { | |
if (!executorService.awaitTermination(10, TimeUnit.MINUTES)) { | |
System.err.println("Waited for 10 minutes, forced exit"); | |
System.exit(0); | |
} | |
} catch (InterruptedException e) { | |
e.printStackTrace(); | |
} | |
} | |
static void run(Object[] arr) { | |
for (Object o : arr) { | |
System.out.println(o); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment