Sobes.tech
Junior — Middle

Milliseid ExecutorService liidese rakendusi teate ja kuidas need erinevad?

sobes.tech AI

Vastus AI-lt

ExecutorService is an interface for managing a thread pool and executing tasks asynchronously. The main implementations from the Java standard library:

  • ThreadPoolExecutor — the most flexible and commonly used implementation, allows configuring the pool size, task queue, and overload policy.
  • ScheduledThreadPoolExecutor — an extension of ThreadPoolExecutor, supports scheduling tasks with delay or periodic execution.
  • ForkJoinPool — designed for tasks that can be divided into subtasks (used in the Fork/Join framework), efficient for parallel computations.

Differences:

  • ThreadPoolExecutor is suitable for general purposes.
  • ScheduledThreadPoolExecutor — for timer-based tasks.
  • ForkJoinPool — for recursive parallelism.

Example of creating a ThreadPoolExecutor:

ExecutorService executor = Executors.newFixedThreadPool(4);
executor.submit(() -> System.out.println("Task completed"));
executor.shutdown();