Thread pool in java:-
In large scale application, multithreading is commonly used to execute
independent
tasks. Now imagine 100 classes extending the Thread class
(or implementing the
runnable interface) and each one having its own run
method and you are asked to write
those run methods. Obviously, you
need to repeat the same code and managing that
code even becomes more
difficult.
A very simple solution to this is to build a thread pool where in you will have a queue
of objects on which the run method will
be called. Any pre-pocessing will be done in
the objects own member
methods. Its only that the tasks will be added to the queue
and an
infinite loop will look for yet to run threads and will run them. You
need two
queues, one containing the threads that are currently running
and other containing those yet to be run.
These queues can be LinkedLists.
1) Maximum and minimum number of threads pending for execution can be controlled.
2) Maximum alive time for each thread can be controlled
3) Many other business requirements in terms of multithreading can be achieved at a central point.
4) Your application’s multithreading is segregated which makes it look decent and well managed and gives a good impression to the reviewer.
5) Your life becomes much easier.
How to achieve it:
1) Create a class to maintain the threadpool information like the read and running queues, the variables for max and min number of threads, time to keep a thread alive
2) A class which contains the loop to check for threads in the running and ready queues and make a decision whether to invoke a particular thread or not.
No comments:
Post a Comment