As Thread, Runnable were part of the multi threaded programming in the initial versions of Java, where as Future, Execution Service and Callable are added in the later version. We can achieve high performance and multi tasking using both ways, but here are few guidelines which you can use to decide what to use.
Hope you find these guidelines useful and leave your comments below.
How many threads will you be launching and how frequently are they used?
If you use lot of threads and there are always tasks to perform using threading, then you could use Execution Service. Examples include processing user requests on high traffic websites etc. But if you have to launch the threads only once in a while for batch cleanup or report generation etc, then you can launch the thread using Thread class. This way you will be saving resources by preventing the execution service running all the time.
This will decide whether to use ExecutionService or Thread.
Does the calling thread need to know the status of the task?
If the calling thread need to know the status of the task, then it is better to use Callable. Callable actually is a replacement for Runnable, but was given a different name to achieve backward compatibility. So where ever you want to use Runnable, you can use Callable. But if you have Java code prior to 1.5 and it only knows Runnable, then you can use it.
This will decide whether to use Runnable or Callable.
This will decide whether to use Runnable or Callable.
Hope you find these guidelines useful and leave your comments below.
Other important notes:
- We need either Thread or ExecutionService for doing tasks parallely, just Runnable or Callable can not achieve multi threading.
- ExecutionService is a pool of threads and hence uses Threads internally.
- If required you can convert a Callable object into a Runnable using some simple wrapper classes.
References:
No comments:
Post a Comment