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:-
There are several ways to assign task to ExecutorService. It has methods like execute, submit ,invokeAny ,invokeAll which take a runnable or callable object.
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.
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)
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.
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:-
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
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.
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.
That’s all about the ThreadPoolExecutor and ScheduledThreadPoolExecutor .I hope you enjoyed reading this article.Happy Coding .
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.
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 .
That’s about creating and starting threads in Java.I hope you enjoyed reading this article. Happy Coding everyone 🙂
Privacy & Cookies Policy
Necessary cookies are absolutely essential for the website to function properly. This category only includes cookies that ensures basic functionalities and security features of the website. These cookies do not store any personal information.