Executorservice in Java

You might also like

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 33

ExecutorService

in Java
What is ExecutorService
• The Java ExecutorService interface, or TreadPoolExecutor
 java.util.concurrent.ExecutorService , represents an
asynchronous execution mechanism which is capable of executing
tasks (Runnable Type Task) concurrently in the background.

• Goals:
1.  user can set the size of the Thread Pool.
2. The ExecutorService creates and maintains a reusable pool of
threads for executing submitted tasks.
3. user can submit tasks to the ExecutorService.
4. It is the Responsibility of ExecutorService to execute
submitted task.
?How to create a ExecutorServisce
: Ideal Pool Size
1. Core Intensive :
it depends on the type of tasks you want to execute .
• IO intensive :
like -> HTTP Requast , URL or Request from Databse
: Summery

Information Ideal Pool Size Task Type :

How many other Number of cores . CPU Intensive :


applications(Threads/Task)
running on the CPU
Depend on rate of task Higher than number of IO Intensive :
submissions , and average cores .
task wait time .
But too many threads can
reduce memory
consumption.
: Pool Types
1. FixedThreadPool.

2. CashedThreadPool.

3. SynchronousThreadPool.

4. SingleThreadedPool.
:Pool Types (cont)
:Pool Types (cont)
:Pool Types (cont)
:Pool Types (cont)
:Pool Types (cont)
:Pool Types (cont)
:Pool Types (cont)
Benefits of Executor framework:

• With an executor, we have to create tasks which


implement either Runnable or Callable interface and
send them to the executor.

• Executor is responsible for executing the tasks, running


them with the necessary threads from the pool.
: Pool size changes
• ThreadPoolExecutor Constructor takes multiple things :

1. Core pool size -> initial pool size -> int

2. Max Pool size -> maximum number of threads the pool can
take , it depends on the pool type -> int .
3. keepAliveTime-> the time the thread stays alive -> long.

4. TimeUnit (millisecond , second , minute ) -> Unit


5. BlockingQueue <Runnable >  work queue .
: Pool Size changes
: Pool Size
singelThreaded SchedualdedPool CashedThreadPool FixedThreadPool CorePoolSize

1 What the user 0 What the user CorePoolSize


puts in the puts in the
constructor . constructor .

1 Integer.MaxValue Integer.MaxValue Same as coreSize MaxPoolSize

0 second 60 second 60 second Not applicable KeepAliveTime


(0 seconds)
: Type of Queues

FixedThreadPool

LinkedBlockingQueue
SingleThreaded

Queue SyncronousQueue CashedThreadQueue

DelayedWorkQueue ScedualedThreadPool
: Rejection Handler
1. Abort Policy : submitting new task throws
RejectedExcutionException (Runtime Exception).

2. Discard Policy : submitting new tasks Silently discards it .

3. Discard Oldest Policy : submitting new tasks drops existing


oldest task , and the new task is added to the queue .

4. Caller Runs policy : submitting new tasks will execute the


task on the caller thread itself . This can create feedback
loop where caller thread is busy executing the task and
cannot submit new tasks at fast pace.
: Shutting Down

1. Service.shutdown : initiate shutdown for the thread pool .

2. Service.isShutdown : returns true if there is initiate shutdown.

3. Service.isTerminated : returns true if all tasks are completed ,


including the ones in the queue.

4. Service.awaitTermination:block until all tasks are completed


or timeout occurs .

5. Service.shutdownNow : will initiate shutdown and return all


queued tasks.
: Callable And future

• It’s a public interface Callable<V>.

• A task that returns a result and may throw an exception.

• Implementers define a single method with no arguments


called call.

• The Callable interface is similar to Runnable, in that both are


designed for classes whose instances are potentially executed
by another thread. A Runnable, however, does not return a
result and cannot throw a checked exception.
:Runnable vs. Callable in Java
1. Execution Mechanism:
Both interfaces are designed to represent a task that can
be executed by multiple threads. Runnable tasks can be
run using the Thread class or ExecutorService whereas
Callables can be run only using the latter.
2. Return Values:
The Runnable interface is a functional interface and has a •
single run() method which doesn't accept any
.parameters and does not return any values
Runnable vs. Callable in Java : )Cont(

• The Callable interface is a generic interface


containing a single call() method – which returns
a generic value V :
Runnable vs. Callable in Java : )Cont(
3. Exception Handling:
Runnable: Since Run method signature does not have the
“throws” clause specified, there is no way to propagate
further checked exceptions. While Callable's call() method
contains “throws Exception” clause so we can easily propagate
checked exceptions further.

4. Thread can’t be created with a Callable, it can only be


created with a Runnable.
: Future

• When the call() method completes, answer must be stored in


an object known to the main thread, so that the main thread
can know about the result that the thread returned. How will
the program store and obtain this result later? For this, a
Future object can be used. Think of a Future as an object that
holds the result – it may not hold it right now, but it will do so
in the future (once the Callable returns). Thus, a Future is
basically one way the main thread can keep track of the
progress and result from other threads. 
: Future
•  To implement this interface, 5 methods have to be
overridden.
:Future example
: Future
• There is a version of the get() method which can time out after
an amount of time has passed which you can specify via
method parameters. 
: Cancel Task via Future cancel
• You can cancel the asynchronous task represented by a
Java Future instance by calling the Future cancel() method..
Here is an example of canceling a task via the
Java Future cancel() method:
Check if Task is Done :

• You can check if the asynchronous task is done (and a result


available) by calling the Future isDone() method. Here is an
example of calling the Java Future isDone() method:
Check if Task is Cancelled :

• it is also possible to check if the asynchronous task


represented by a Java Future is cancelled. Here is an example
of checking if a task was cancelled:
Done By :
Nawras Hawamdeh , Noor Hamamrah , Isra’ Shalan

You might also like