Last active
January 6, 2026 22:46
-
-
Save bdelacretaz/721829725aca009246b5b163d33ea630 to your computer and use it in GitHub Desktop.
Example thread pool that pulls tasks from a Supplier
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
| import java.util.concurrent.Callable; | |
| import java.util.concurrent.atomic.AtomicInteger; | |
| import java.util.function.Supplier; | |
| // Example of a thread pool that pulls tasks from a Supplier | |
| public class PullingPool { | |
| public static void main(String[] args) throws Exception { | |
| final int nThreads = (int) (Math.random() * 4) + 2; | |
| final int nTasks = (int) (Math.random() * 45) + 5; | |
| final AtomicInteger supplierId = new AtomicInteger(nTasks); | |
| final String marker = "****** "; | |
| System.out.println(marker + "Running " + nTasks + " tasks with " + nThreads + " threads"); | |
| // Supplier of tasks, will be called by the thread pool, | |
| // returns null if no more tasks to run | |
| final Supplier<Callable> supplier = () -> { | |
| final int id = supplierId.decrementAndGet(); | |
| if (id < 0) { | |
| // we're done | |
| return null; | |
| } | |
| return new Callable() { | |
| @Override | |
| public Object call() throws Exception { | |
| final int wait = (int) (Math.random() * 250); | |
| Thread.sleep(wait); | |
| return String.format("%s (%d msec)", id, wait); | |
| } | |
| }; | |
| }; | |
| // Thread pool, each thread loops until the task supplier returns a null Callable | |
| for (int i = 0; i < nThreads; i++) { | |
| final int id = i; | |
| final AtomicInteger executed = new AtomicInteger(); | |
| new Thread(() -> { | |
| while (true) { | |
| try { | |
| final Callable task = supplier.get(); | |
| if (task == null) { | |
| System.out.println(marker + "Thread " + id + ": done, ran " + executed.get() + " tasks"); | |
| break; | |
| } | |
| System.out.println("Thread " + id + " ran task " + task.call()); | |
| executed.incrementAndGet(); | |
| } catch (Exception whatShallWeDo) { | |
| whatShallWeDo.printStackTrace(); | |
| } | |
| } | |
| }).start(); | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment