Sobes.tech
Junior — Middle

What methods can be used to implement or create an ExecutorService interface in Java?

sobes.tech AI

Answer from AI

The ExecutorService interface in Java can be implemented in several ways, depending on the requirements for thread and task management:

  1. Extending AbstractExecutorService — this is an abstract class that already implements part of the ExecutorService logic. You can create your own class that extends it and implement the necessary methods.

  2. Implementing the ExecutorService interface directly — you need to implement all the interface methods, including lifecycle management, task execution, termination, etc. This is more labor-intensive.

  3. Using existing implementations and their wrappers — for example, you can create a class that internally uses ThreadPoolExecutor or other implementations and delegates calls to them.

An example of a simple implementation extending AbstractExecutorService:

import java.util.concurrent.*;

public class SimpleExecutorService extends AbstractExecutorService {
    private volatile boolean running = true;

    @Override
    public void shutdown() {
        running = false;
    }

    @Override
    public List<Runnable> shutdownNow() {
        shutdown();
        return Collections.emptyList();
    }

    @Override
    public boolean isShutdown() {
        return !running;
    }

    @Override
    public boolean isTerminated() {
        return !running;
    }

    @Override
    public boolean awaitTermination(long timeout, TimeUnit unit) throws InterruptedException {
        Thread.sleep(unit.toMillis(timeout));
        return isTerminated();
    }

    @Override
    public void execute(Runnable command) {
        if (running) {
            new Thread(command).start();
        } else {
            throw new RejectedExecutionException("ExecutorService is shutdown");
        }
    }
}

This example runs each task in a new thread, which is inefficient for a large number of tasks but demonstrates the basic principle of implementation.

What methods can be used to implement or create an… - sobes.tech