Java concurrency and executors framework example

Executors framework

Threads that comes with low level API from Thread class are available from the beginning of Java language, that is not suitable or ready to use directly in large applications that need a huge number of parallel or concurrent process.

Executors APIs are adequate for massively concurrent applications that fully exploit today’s multiprocessor and multi-core systems. And provides you the Highlevel API to manage threads creations and execution.

Executors class

Executors class provides you the factory and utility methods for below interface

  • Executor
  • ExecutorService
  • ScheduledExecutorService
  • ThreadFactory
  • Callable

Some of the utility methods are

  • callable
  • defaultThreadFactory
  • newCachedThreadPool
  • newFixedThreadPool
  • newSingleThreadExecutor
  • newSingleThreadScheduledExecutor
  • newScheduledThreadPool


Executor Interface

The Executor interface provides a single method execute() as a drop in replacement of old thread creation methods

Example assume we have a runnable object,

Runnable r=new MyTask();

new Thread(r).start();

We can replace the thread creation with


execute method will do the same work as we do with lowlevel API(new Thread(r).start()), but differs in thread creation and managing it based on its implementation.

ExecutorService Interface

ExecutorService interface extends the Executor Interface and provides more methods like

  • execute
  • submit
  • shutdownNow
  • shutdown
  • isTerminated
  • isShutdown
  • invokeAny
  • invokeAll
  • awaitTermination

ScheduledExecutorService interface

ScheduledExecutorService interface extends ExecutorService, An ScheduledExecutorService that can schedule commands to run after a given delay or to execute periodically. ScheduledExecutorService provides you some extra functionality like

  • schedule
  • scheduleAtFixedRate
  • scheduleWithFixedDelay

ThreadFactory Interface

An object that creates new threads on demand. Using thread factories removes hardwiring of calls to new Thread, enabling applications to use special thread subclasses, priorities, etc.

Callable Interface

The Callable interface is similar to Runnable, in that both are designed for classes whose instances are potentially executed by another thread.

A callable task can return a result and may throw an exception. Implementors define a single method with no arguments called call.

A Runnable, however, does not return a result and cannot throw a checked exception.

Leave a Reply

Your email address will not be published. Required fields are marked *