Hackforge Academy

Category: java

What Is ExecutorService?

Published on 27 Oct 2026

Explanation

ExecutorService manages task execution using a pool or other executor strategy. It separates submitting work from managing threads and offers lifecycle methods such as shutdown() and awaitTermination().

Code:

import java.util.concurrent.*;

public class ExecutorIntro {
    public static void main(String[] args) {
        ExecutorService pool = Executors.newFixedThreadPool(2);
        pool.submit(() -> System.out.println("Task executed"));
        pool.shutdown();
    }
}

Explanation

A fixed thread pool uses a configured number of worker threads. It can limit concurrent execution, but the standard fixed-pool factory uses an unbounded queue, so applications should consider queue growth under heavy load.

Code:

import java.util.concurrent.*;

public class FixedPoolDemo {
    public static void main(String[] args) {
        ExecutorService pool = Executors.newFixedThreadPool(3);
        for (int i = 1; i <= 5; i++) {
            int id = i;
            pool.submit(() -> System.out.println("Task " + id));
        }
        pool.shutdown();
    }
}

Explanation

execute() accepts Runnable and does not return a result handle. submit() accepts Runnable or Callable and returns a Future. Exceptions from submitted tasks can be observed through Future.get().

Code:

import java.util.concurrent.*;

public class SubmitExecuteDemo {
    public static void main(String[] args) throws Exception {
        ExecutorService pool = Executors.newSingleThreadExecutor();
        try {
            pool.execute(() -> System.out.println("execute task"));
            Future<Integer> f = pool.submit(() -> 42);
            System.out.println(f.get());
        } finally { pool.shutdown(); }
    }
}

Explanation

shutdown() stops accepting new tasks but lets submitted tasks finish. shutdownNow() attempts to interrupt running tasks and returns queued tasks that never commenced; it does not guarantee immediate termination.

Code:

import java.util.concurrent.*;

public class ShutdownDemo {
    public static void main(String[] args) throws InterruptedException {
        ExecutorService pool = Executors.newFixedThreadPool(2);
        pool.submit(() -> System.out.println("Finishing task"));
        pool.shutdown();
        if (!pool.awaitTermination(2, TimeUnit.SECONDS)) pool.shutdownNow();
    }
}

Explanation

A Future returned by submit() represents a task's outcome. Calling get() waits for completion and can throw ExecutionException if the task failed, or InterruptedException if the waiting thread is interrupted.

Code:

import java.util.concurrent.*;

public class FutureExceptionDemo {
    public static void main(String[] args) {
        ExecutorService pool = Executors.newSingleThreadExecutor();
        try {
            Future<Integer> f = pool.submit(() -> 10 / 0);
            try { System.out.println(f.get()); }
            catch (ExecutionException e) { System.out.println("Task failed: " + e.getCause()); }
            catch (InterruptedException e) { Thread.currentThread().interrupt(); }
        } finally { pool.shutdown(); }
    }
}

πŸš€ Learn Spring Boot with real-world projects

πŸ’‘ Build REST APIs step by step

🧠 Improve backend development skills

🎯 Get career-ready practical training

Join Our Free WhatsApp Community

Direct access to niche-specific mentors and peers on WhatsApp.

🐍

Python Community

Discuss Django, FastAPI, AI integration, and automation scripts with 15k+ developers.

Join Python Community
βš›οΈ

React Community

Master Next.js, Framer Motion, and State Management. Share your latest UI components.

Join React Community
β˜•

Java Community

Deep dives into Spring Boot, Microservices architecture, and high-performance backend ops.

Join Java Community