Java
ExecutorService
Task Prioritization
Java 5
Multithreading

How do I implement task prioritization using an ExecutorService in Java 5?

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

Introduction

Java 5 ExecutorService does not include built-in task priority scheduling with fixed thread pools. To prioritize tasks, use ThreadPoolExecutor backed by a PriorityBlockingQueue and submit tasks that implement Comparable. This gives deterministic ordering while keeping standard executor lifecycle controls.

Core Design with PriorityBlockingQueue

A priority queue orders tasks by compare rules. Lower numeric priority can represent higher urgency if you define it that way consistently.

java
1import java.util.concurrent.*;
2
3public class PriorityExecutorDemo {
4
5    static class PriorityTask implements Runnable, Comparable<PriorityTask> {
6        private final int priority;
7        private final String name;
8
9        PriorityTask(int priority, String name) {
10            this.priority = priority;
11            this.name = name;
12        }
13
14        @Override
15        public int compareTo(PriorityTask other) {
16            return Integer.compare(this.priority, other.priority);
17        }
18
19        @Override
20        public void run() {
21            System.out.println("Running " + name + " with priority " + priority);
22        }
23    }
24
25    public static void main(String[] args) throws Exception {
26        BlockingQueue<Runnable> queue = new PriorityBlockingQueue<Runnable>();
27        ThreadPoolExecutor executor = new ThreadPoolExecutor(
28            2, 2, 0L, TimeUnit.MILLISECONDS, queue
29        );
30
31        executor.execute(new PriorityTask(5, "low"));
32        executor.execute(new PriorityTask(1, "high"));
33        executor.execute(new PriorityTask(3, "medium"));
34
35        executor.shutdown();
36        executor.awaitTermination(5, TimeUnit.SECONDS);
37    }
38}

This is Java 5 compatible and avoids newer APIs.

Preserve FIFO for Same Priority

Priority queues do not guarantee insertion order for equal priority values. Add a sequence number for stable ordering.

java
1import java.util.concurrent.atomic.AtomicLong;
2
3static final AtomicLong SEQ = new AtomicLong();
4
5static class StablePriorityTask implements Runnable, Comparable<StablePriorityTask> {
6    private final int priority;
7    private final long seq;
8    private final String name;
9
10    StablePriorityTask(int priority, String name) {
11        this.priority = priority;
12        this.name = name;
13        this.seq = SEQ.getAndIncrement();
14    }
15
16    public int compareTo(StablePriorityTask other) {
17        int p = Integer.compare(this.priority, other.priority);
18        if (p != 0) return p;
19        return Long.compare(this.seq, other.seq);
20    }
21
22    public void run() {
23        System.out.println(name);
24    }
25}

This keeps behavior deterministic and easier to debug.

Wrapping Callable with Priority

If your tasks return values, wrap Callable and submit through custom holder classes. The queue must compare wrapper instances, not plain FutureTask.

A practical pattern is creating a custom RunnableFuture in a subclassed ThreadPoolExecutor and injecting priority metadata during submission.

Operational Considerations

Prioritization can starve low-priority tasks. Prevent starvation by reserving time slices for lower tiers or periodically aging waiting tasks.

Also monitor queue length per priority bucket. Without metrics, teams often discover starvation only after user-visible delays.

Shutdown behavior remains standard. Always call shutdown and awaitTermination for graceful service stop.

Submitting Callable Tasks with Priority Metadata

When results are needed, create a prioritized wrapper and convert it into FutureTask through a custom executor subclass.

java
1import java.util.concurrent.*;
2
3class PriorityCallable<V> implements Callable<V>, Comparable<PriorityCallable<V>> {
4    final int priority;
5    final Callable<V> delegate;
6
7    PriorityCallable(int priority, Callable<V> delegate) {
8        this.priority = priority;
9        this.delegate = delegate;
10    }
11
12    public V call() throws Exception {
13        return delegate.call();
14    }
15
16    public int compareTo(PriorityCallable<V> other) {
17        return Integer.compare(this.priority, other.priority);
18    }
19}

Then adapt submission paths so queue ordering uses wrapper priority consistently.

Testing Fairness and Starvation

Add integration tests with mixed workloads to confirm high-priority tasks are preferred without starving lower-priority tasks forever. One approach is measuring max wait time per priority bucket and alerting when low-priority backlog exceeds a threshold.

Operational metrics such as queue size and average task age should be exported so behavior stays visible after deployment.

Common Pitfalls

A common pitfall is using Executors.newFixedThreadPool directly, which does not expose queue type selection for priority ordering.

Another issue is submitting lambdas or anonymous runnables without priority metadata. Those cannot be ordered meaningfully.

Type mismatches can also occur if queue expects comparable tasks but receives plain runnables.

Finally, test with load. Priority logic that appears correct in tiny examples can behave differently under contention.

Summary

  • Use ThreadPoolExecutor with PriorityBlockingQueue for priority scheduling in Java 5.
  • Implement Comparable on task wrappers to define ordering.
  • Add sequence numbers to keep FIFO for equal priority.
  • Watch for starvation and add fairness strategies when needed.
  • Keep lifecycle management and metrics in place for production use.

Related reading
Course
Intermediate
27 lessons
14 hours
OOD Fundamentals

Master object-oriented design from first principles, SOLID, design patterns, and classic interview problems with hands-on coding.

View the course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions