Callable Vs Runnable Interface

Both Callable and Runnable are interfaces used to define task supposed to be executed by a separate thread.Also, both of them can be used with lambda expressions. But there are key differences between the two interfaces.

  • Callable interface can return the result of the task defined to be executed whereas Runnable does not return any result .Callable return a Future object which has methods to fetch the result of the task, check if the task has been completed or cancelled etc.
  • Callable can throw checked exceptions whereas Runnable does not throw any exceptions.
  • Callable is a functional interface which is added in Java 1.5 whereas Runnable exists since Java 1.0
  • Callable has call() method which needs to be overriden to define the task whereas Runnable has run() method which needs to be overriden
  • You can not pass the Callable to a Thread ,the way you pass the Runnable Object.You need to use the ExecutorService interface to execute the Callable interface.The interface defines the submit method which takes the Callable object and return a Future Object to retrieve the result.

Runnable Example

Runnable Interface Example

Since runnable interface does not return any result so future.get() method returns null.

Callable Example

Callable Interface Example

In case of callable return the result of the task which is retrieved by future.get() method.

Future Interface

Future has several API to help us with the processing task.

Future.isDone() method tells us if the task has been processed or not.If the task is processed it returns true else false.

Future.get() method returns the actual result of the task being processed.This method blocks the execution until the task is complete.

Future.cancel() method stop the execution of the task and interrupts its underlying thread.If we try to call Future.get() method after the cancel() method ,CancellationException is thrown.

Future.isCancelled() method tells if a future is already cancelled. It return true if it was cancelled .

References:- Java 8 API Documentation

That’s all about Runnable , Callable and Future interface.Happy Coding 🙂

Java Executor Framework Tutorial

The concurrency API in Java was introduced in Java 1.5 .Java Executor framework is used to run the Runnable objects without creating new threads and reusing the existing ones as creating threads is an expensive process. It simplifies the execution of tasks in asynchronous mode.


An ExecutorService is created using Executors factory methods. The main thread delegates the task to the ExecutorService and it executes the task concurrently, independent of the thread that submitted the task.

ExecutorService is an interface and it has the following implentations:-

Creating ExecutorService

ExecutorService executorService1 = Executors.newSingleThreadExecutor();

ExecutorService executorService2 = Executors.newFixedThreadPool(10);

ExecutorService executorService3 = Executors.newScheduledThreadPool(10);

Delegating tasks to ExecutorService

There are several ways to assign task to ExecutorService. It has methods like execute, submit ,invokeAny ,invokeAll which take a runnable or callable object.


Executor Service Example

The execute service take a runnable object and executes it asynchronously. In the above example I have created an anonymous runnable object and passed it to the execute method.


The execute() method has void return type and its doesn’t return the result of the task execution.

The submit() method take a runnable or callable object and return a Future object.The Future.get() method returns the result of the task.In case of Runnable it returns null if the task has been successfully.

The Callable result can be obtained by the Future’s object using the get method.

Callable Example


The invokeAll() method assigns a collection of tasks to ExecutorService and each of the task is executed.The ExecutorService returns a list of Future Objects and we can obtain the result of the all the callable objects submitted for execution.

The invokeAny() method takes a collection of Callable Objects.It returns the result of one of the Callable Object but there’s is no guarantee which of the Callable result is returned.The ExecutorService returns the result of one of the successful task (if there’s any)

ExecutorService Shutdown

To stop the threads from running in ExecutorService ,the shutdown() method is used.The ExecutorService will not shut down immediately it will no longer accept new tasks.All the tasks submitted before calling the shutdown method are executed.


There is another shutdown method called shutdownNow() which shuts down the ExecutorService immediately. This will stop all executing tasks and skip all submitted but non processing tasks. There is no guarantee given to the executing tasks.


The ExecutorService awaitTermination() method will block the thread calling it until the ExecutorService has shutdown completely or until a given time out occurs. Its usually called after shutdown() or shutdownNow() method.


References:- Oracle Docs

That’s all about ExecutorService .I hope you enjoyed reading this article.Happy Coding 🙂

ThreadPoolExecutor and ScheduledThreadPoolExecutor


ThreadPoolExecutor implements ExecutorService .It executes each submitted tasks using one of its internally pooled threads.Thread pools provide improved performance when executing large number of asynchronous tasks.This class provides many adjustable parameters and extensibility hooks. But usually ExecutorFactory methods are used to create thread pool.

You can configure the no of threads in the ThreadPoolExecutor using the following variables:-

  • corePoolSize
  • maximumPoolSize

The ThreadPoolExecutor automatically adjust the pool size as per the bounds set by corePoolSize and maximumPoolSize.When a new task is submitted and fewer than core pool threads are running , a new thread is created to handle the request ,even if other threads are idle.If there are more than corePoolSize threads but less than maximumPoolSize threads running, a new thread is created only if the queue is full. Typically maximum and core pool size are set at the time of construction but they can also be set dynamically using the setter methods for maximum and core pool size. If the corePoolSize and maximumPoolSize is same a fixed size thread pool is created.

The ThreadPoolExceutor has several constructors available and you can specify corePoolSize ,maximumPoolSize, keepAliveTime, timeUnit, BlockingQueue and also ThreadFactory and RejectedExceutionHandle

ThreadPoolExecutor Example



ScheduledThreadPoolExceutor can additionally schedule commands to run after a given delay or to execute periodically. This class is preferable when multiple threads are needed or when the additional capabilities of ThreadPoolExecutor is required.

Delayed tasks are executed no sooner than they are enabled, but without any guarantee about when , after they are enabled ,they will commence.

When a submitted task is cancelled before it is run ,execution is suppressed. By default such a cancelled task is not automatically removed from the work queue until the delay lapses.This enabled further inspection and monitoring but it may also lead to unbounded retention of cancelled tasks. To avoid this you can set setRemoveOnCancelPolicy(boolean) to true, which causes tasks to be immediately removed from the work queue at the time of cancellation. Successive execution of a tasks scheduled via scheduledAtFixedRate or scheduledWithFixedDelay do not overlap.While different executions may be performed by different threads ,the effect of prior execution happen before those of subsequent ones.

The schedulexxx() methods of ScheduledPoolExceutor accept instance of Runnable or Callable.You can get the result of computation of the Callable instance via get() method of ScheduledFuture.


ScheduledThreadPoolExecutor Example

In the above example a scheduled thread pool is created with a thread pool of 5 threads . A runnable and callable task is created which is passed to the executor service .The runnable task is scheduled to run with a fixed delay of 1 second and the callable task is scheduled to execute after a delay of 3 seconds.


References:- Oracle Docs

That’s all about the ThreadPoolExecutor and ScheduledThreadPoolExecutor .I hope you enjoyed reading this article.Happy Coding .

How to create Threads in Java

What is a Thread?

A thread is a light weight process.Java provides built in support for multithreading. A multithreaded program contain several parts than can run concurrently. Each part is a thread which has a separate thread of execution. A thread exists within a process and a single process can contain multiple threads.

Lifecycle of a Thread

A thread goes through various stages in its life cycle.Here’s the various states of a thread:-

  • New :- When we create an instance of a thread ,its in a new state
  • Runnable :- A thread is in runnable state after invocation of start method but it has not been selected by the schedular for execution.
  • Running :- Java Thread is in running state.
  • Blocked :- A thread can be in a blocked state waiting for a resource.
  • Terminated :- A thread can be terminated which stops its execution.A thread cant be resumed after termination.

Threads can be created in two ways

  • By extending thread class
  • By implementing Runnable interface

Extending Thread class

Threads can be created by extending the Thread class .Here’s an example:-

Here we are extending the Thread class and overriding the run method .In the run method we define task/business logic to be executed in the thread.

Then we create the instance of our thread class and and start the thread.

Extending Thread Class Example

Running the program results in the following output:-

The output may change every time you run the program depending on which thread is executed.

Implementing Runnable Interface

We can also create a thread by implementing the Runnable interface.

Then we create an instance of Runnable object (that’s our custom object) and pass this instance to the Thread object.

We start the thread using Thread start() method.

Please note that the output may vary every time you run the program .

References:- Oracle Docs

That’s about creating and starting threads in Java.I hope you enjoyed reading this article. Happy Coding everyone 🙂

Convert Clob Type to String In Java

An SQL clob to used to store large amount of textual data in the database.The sql clob interface represents the clob data type.

In this tutorial I am going to explain how to convert clob to string in Java.

In an ideal scenario you read the clob data from the database and convert it to String and display it on console and may be display it on a UI(User Interface)

Steps to convert Clob to String

  • Read the clob value using getCharacterStream() method.
Reader r = clobData.getCharacterStream();
  • Read each character one by one from the retrieved stream of characters and append it to string buffer.
StringBuffer buffer = new StringBuffer();
int ch;
while ((ch =!=-1) {
  • Display the obtained String


Clob Type to String Example

Happy Learning 🙂