From: Robin Cheney Date: Tue, 25 Nov 2025 10:16:40 +0000 (+0100) Subject: 1.4.0: added Parallel Processing X-Git-Url: https://git.eternal.ddnss.de/?a=commitdiff_plain;h=ff960a0a29b2795482924b46515ae7c0f9bb5b9f;p=utils.git 1.4.0: added Parallel Processing --- diff --git a/pom.xml b/pom.xml index e1cfaaa..8bab3be 100644 --- a/pom.xml +++ b/pom.xml @@ -6,7 +6,7 @@ de.ddnss.eternal.utils utils - 1.3.3 + 1.4.0 UTF-8 diff --git a/src/main/java/de/ddnss/eternal/utils/threading/ParallelProcessor.java b/src/main/java/de/ddnss/eternal/utils/threading/ParallelProcessor.java new file mode 100644 index 0000000..cea151d --- /dev/null +++ b/src/main/java/de/ddnss/eternal/utils/threading/ParallelProcessor.java @@ -0,0 +1,41 @@ +package de.ddnss.eternal.utils.threading; + +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.ThreadPoolExecutor; +import java.util.concurrent.TimeUnit; +import java.util.function.Supplier; + +public class ParallelProcessor { + + public static void run(Runnable function, int threads) { + ThreadPoolExecutor executor = (ThreadPoolExecutor) Executors.newFixedThreadPool(threads); + for (int i = 0; i < threads; i++) { + executor.submit(function); + } + } + + /** + * Runs the given task repeatedly using the given number of threads until + * the provided condition becomes true. + */ + public static void runUntil(Runnable task, int threads, Supplier stopCondition) { + ExecutorService executor = Executors.newFixedThreadPool(threads); + + for (int i = 0; i < threads; i++) { + executor.submit(() -> { + while (!stopCondition.get()) { + task.run(); + } + }); + } + + executor.shutdown(); + + try { + executor.awaitTermination(Long.MAX_VALUE, TimeUnit.DAYS); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } + } +}