Reputation:
In java, will adding multiple threads to do one task in java help in executing that task faster?
currently the main thread was used in my program, but it was slow. My current measurements were 500 process per second, but the total number of processes were over a billion. How can I make my program runs faster?
Upvotes: 0
Views: 143
Reputation: 1499750
In java, will adding multiple threads to do one task in java help in executing that task faster?
It entirely depends on what you're doing. If you're performing tasks on independent pieces of data, with no bottleneck in either retrieving or storing the results, and assuming you're on a machine with more than one processor then yes, using more threads is likely to help.
However, there are various ways it can not help:
In some of these cases threading can help, but not as significantly as if it's just CPU bound and you have plenty of spare cores. You need to work out where your current bottlenecks are.
Note that in the best case you're only going to get a speed-up proportional to the number of cores you've got. So if you've got 16 cores (unlikely but feasible) and perfect parallelization, then if one core can process 500 items per second and you've got a billion items, it's still going to take nearly 35 hours to process everything.
One thing which is almost certain is that your multi-threaded code will be more complicated than you single-threaded code. Try to use high-level abstractions (e.g. the ones in java.util.concurrent
instead of low-level ones (such as java.lang.Thread
) to make things simpler.
Upvotes: 3