Tuesday, 18 May 2021

Thread Pool

Thread pool is a solution to limit the number of threads in usage, and so as to avoid the lower performance and system crash due to resource exhaustion.  

A thread pool is a group of pre-instantiated, idle threads that stand ready to be given work. Using a thread pool gives a better performance than creating a new thread for each task. It uses existing thread first, only having no existing available, then creating a new thread.

ExecutorService extends Executor

ScheduleExecutorService extends ExecutorService

ExecutorService manages to submit tasks much better than Executor. It accepts both Runnable and Callable.

ScheduleExecutorService manages to submit tasks and run in planned time slices.


ExecutorService offer APIs 

'IsTerminated()': testing if all submitted tasks having been accomplished.

'IsShutDown()': testing if the executor is shut down. 

'shutDownNow' means that attempting to halt active running threads, and stop picking up tasks from the queue, and returning un-implemented tasks in a collection. 'shutDownNow' is more like shutting down at once.


'shutDown' means executing previously accepted tasks, but no more task accepted; if you do add one after it; it won't give a compiling error, but a run-time exception, i.e. java.util.concurrent.RejectedExecutionException

Through ExecutorSerive, the client may submit Runnable or callable to the thread pool.

Executor consists of a queue and a pool.

Pool types: fixed-sized, single thread, scheduled thread pool, cached thread pool

The 'Executors' is a factory, where a client achieve a specific type of thread pool.

       ExecutorService es = Executors.newCachedThreadPool();

        es.execute(new PrintChar(10, 'a'));
        es.execute(new PrintNum(10, 66));
        es.execute(new PrintNum(10, 20));
        es.shutdown();

No comments:

Can Jackson Deserialize Java Time ZonedDateTime

Yes, but must include JSR310. Thus ZonedDateTime can be deserialized directly from JSON response to POJO field. <dependency> <g...