Skip to content
Java project #25Advanced

Concurrent Task Scheduler

Validate a dependency graph, plan parallel waves and the critical path, then run tasks on a thread pool with CompletableFuture — with retries for flaky tasks and skipping of blocked ones.

Estimated time
~9 hours to build
Files
6 files · 482 lines
Technologies
Java 21, CompletableFuture, ExecutorService, ConcurrentHashMap, TreeMap / TreeSet

Introduction

Build systems, CI pipelines and workflow engines all schedule tasks with dependencies. Underneath they combine graph algorithms (topological order, cycle detection, critical path) with concurrency (start each task as soon as its inputs are ready). This project builds both halves and keeps the output deterministic by printing results only after everything has finished.

Problem statement

Read jobs made of task lines NAME COST [after DEP,...] [flaky N], separated by run. For each job, reject duplicate names, unknown dependencies and cycles (showing the cycle). Plan topological waves of tasks that can run in parallel and compute the critical path and the best possible speed-up. Execute the tasks on a four-thread pool, starting each as soon as its dependencies complete; retry flaky tasks up to three attempts, mark tasks that still fail, and skip tasks whose dependencies didn't complete. Print each task's status and result.

Objectives

  • Detect cycles with a three-colour depth-first search
  • Produce topological waves with Kahn's algorithm
  • Compute a critical path with dynamic programming
  • Compose CompletableFutures to respect dependencies

Features

  • Graph validation with cycle reporting
  • Parallel waves, critical path and speed-up bound
  • Dependency-driven parallel execution
  • Retries, failures and skipped dependents

Concepts demonstrated

  • Directed acyclic graphs
  • Topological sorting
  • Critical path
  • Asynchronous composition
  • Fault handling

System architecture

TaskGraph validates dependencies, finds cycles by DFS (a grey node seen again is a back edge), computes waves with Kahn's algorithm (sorting names within a wave for stable output), and finds the critical path by computing each task's earliest finish over the topological order. Executor creates one CompletableFuture per task in wave order, each starting with allOf(dependencies).thenApplyAsync(...) on the pool; the task body checks that every dependency succeeded, simulates transient failures for flaky tasks, and computes a deterministic CPU-bound result (counting primes). Outcomes go into a ConcurrentHashMap and are printed by Main in wave order once all futures have joined.

TextArchitecture diagram
checkout -> deps -> compile -> unit --------\
\ \-> integration -> package -> deploy
\-> lint ----------------------------/ /
\-> docs -------------------------------------/

Folder structure

TextProject tree
task-scheduler/
├── README.md
├── src/Executor.java
├── src/Main.java
├── src/TaskGraph.java
├── tests/expected-output.txt
└── tests/sample-input.txt

Complete source code

src/Executor.java

88 lines
Javasrc/Executor.java
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionException;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicInteger;
/**
* Runs a TaskGraph on a thread pool with CompletableFuture: each task starts as soon as all of
* its dependencies have completed. Work is simulated with a deterministic CPU-bound computation
* (counting primes), "flaky" tasks fail a set number of times and are retried, and a task whose
* dependency failed for good is skipped. Results are collected in a map and printed in a fixed
* order afterwards, so the report is identical on every run even though execution is parallel.
*/
public class Executor {
public enum Status { DONE, FAILED, SKIPPED }
public record Outcome(String task, Status status, int attempts, long result, String detail) { }
private final int threads, maxAttempts;
private final AtomicInteger peakParallel = new AtomicInteger(), running = new AtomicInteger();
public Executor(int threads, int maxAttempts) {
this.threads = threads;
this.maxAttempts = maxAttempts;
}
public int peakParallel() { return peakParallel.get(); }
public Map<String, Outcome> run(TaskGraph graph) {
Map<String, Outcome> outcomes = new ConcurrentHashMap<>();
Map<String, CompletableFuture<Boolean>> futures = new LinkedHashMap<>();
try (ExecutorService pool = Executors.newFixedThreadPool(threads)) {
for (List<String> wave : graph.waves()) // dependencies always appear in an earlier wave
for (String name : wave) {
TaskGraph.Task t = graph.tasks().get(name);
CompletableFuture<?>[] deps = t.deps().stream().map(futures::get).toArray(CompletableFuture[]::new);
CompletableFuture<Boolean> f = CompletableFuture.allOf(deps).thenApplyAsync(ignored -> {
for (String d : t.deps())
if (outcomes.get(d).status() != Status.DONE) {
outcomes.put(name, new Outcome(name, Status.SKIPPED, 0, 0, "dependency " + d + " did not complete"));
return false;
}
return attempt(t, outcomes);
}, pool);
futures.put(name, f);
}
CompletableFuture.allOf(futures.values().toArray(CompletableFuture[]::new)).join();
} catch (CompletionException e) {
throw new IllegalStateException("scheduler failure: " + e.getCause());
}
return outcomes;
}
private boolean attempt(TaskGraph.Task t, Map<String, Outcome> outcomes) {
int now = running.incrementAndGet();
peakParallel.accumulateAndGet(now, Math::max);
try {
for (int attempt = 1; attempt <= maxAttempts; attempt++) {
if (attempt <= t.failuresBeforeSuccess()) continue; // simulated transient failure
long result = work(t.cost());
outcomes.put(t.name(), new Outcome(t.name(), Status.DONE, attempt, result, attempt > 1 ? "succeeded after " + (attempt - 1) + " retr" + (attempt == 2 ? "y" : "ies") : ""));
return true;
}
outcomes.put(t.name(), new Outcome(t.name(), Status.FAILED, maxAttempts, 0, "failed " + maxAttempts + " times"));
return false;
} finally {
running.decrementAndGet();
}
}
// Deterministic CPU work: the number of primes below cost x 20,000.
static long work(int cost) {
int limit = cost * 20_000;
boolean[] composite = new boolean[limit + 1];
long count = 0;
for (int i = 2; i <= limit; i++) {
if (composite[i]) continue;
count++;
for (long j = (long) i * i; j <= limit; j += i) composite[(int) j] = true;
}
return count;
}
}

What each file does

src/TaskGraph.java
Task definitions, validation, cycle detection, waves and the critical path.
src/Executor.java
CompletableFuture-based execution with retries, failure propagation and the simulated work.
src/Main.java
Parses jobs and task lines, prints the plan and the results.

How to run it

Compile

Terminal
javac -d out $(find src -name "*.java")
# Windows PowerShell: javac -d out (Get-ChildItem -Recurse src -Filter *.java).FullName

Run

Terminal
java -cp out Main

Test against the expected output

Terminal
java -cp out Main < tests/sample-input.txt > actual.txt
diff actual.txt tests/expected-output.txt
# Windows PowerShell:
# Get-Content tests\sample-input.txt | java -cp out Main > actual.txt

Expected output

Generated by running the project with tests/sample-input.txt. Your output should match tests/expected-output.txt exactly.

Texttests/expected-output.txt
===== Job 1 (9 task line(s)) =====
Plan:
wave 1: checkout
wave 2: deps, docs, lint
wave 3: compile
wave 4: integration, unit
wave 5: package
wave 6: deploy
total work 23 units; critical path checkout -> deps -> compile -> integration -> package -> deploy = 16 units (best possible speed-up 1.4x)
Results:
checkout DONE result 2262
deps DONE result 6057
docs DONE result 4203
lint DONE result 4203
compile DONE result 7837
integration DONE result 9592 (succeeded after 2 retries)
unit DONE result 6057
package DONE result 4203
deploy DONE result 2262
9/9 tasks completed; widest wave: 3 task(s) able to run in parallel on the 4-thread pool
===== Job 2 (4 task line(s)) =====
Plan:
wave 1: fetch
wave 2: backup, parse
wave 3: report
total work 8 units; critical path fetch -> parse -> report = 6 units (best possible speed-up 1.3x)
Results:
fetch DONE result 4203
backup DONE result 4203
parse FAILED failed 3 times
report SKIPPED dependency parse did not complete
2/4 tasks completed; widest wave: 2 task(s) able to run in parallel on the 4-thread pool
===== Job 3 (3 task line(s)) =====
Rejected: dependency cycle: a -> c -> b -> a
===== Job 4 (1 task line(s)) =====
Rejected: x depends on unknown task y
Input
# A build pipeline: NAME COST [after DEPS] [flaky N]
checkout 1
deps 3 after checkout
compile 4 after deps
lint 2 after checkout
unit 3 after compile
integration 5 after compile flaky 2
docs 2 after checkout
package 2 after unit,integration,lint
deploy 1 after package,docs
run

# A task that always fails takes its dependents down with it
fetch 2
parse 3 after fetch flaky 5
report 1 after parse
backup 2 after fetch
run

# Invalid: a cycle
a 1 after c
b 1 after a
c 1 after b
run

# Invalid: unknown dependency
x 1 after y
run

Testing

  • Run with tests/sample-input.txt and compare with tests/expected-output.txt.
  • Job 1: the critical path is checkout → deps → compile → integration → package → deploy (16 of 23 units); integration succeeds after 2 retries.
  • Job 2: parse fails three times, so report is skipped while backup still runs.
  • Jobs 3 and 4 are rejected for a cycle (a → c → b → a) and an unknown dependency.

Common errors

A task starts before its dependency finishes

Build each task's future from allOf(its dependencies' futures), not from the order of submission.

The output order changes between runs

Collect outcomes in a concurrent map and print them afterwards in a fixed (wave) order.

Possible improvements

  • Add per-task timeouts with orTimeout
  • Cache results so unchanged tasks are skipped (incremental builds)
  • Export the graph in Graphviz DOT format

Additional challenges

  1. 1Cancel all remaining tasks as soon as one fails (fail-fast mode).
  2. 2Limit tasks tagged 'io' to two at a time with a Semaphore.
  3. 3Measure real elapsed time and compare it with the critical-path bound.

Built and tested it yourself? Mark it to update your dashboard.