0

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?

  • When you are making a cake, will adding 100 people making it together turns out to be faster? – Adrian Shum Nov 16 '12 at 07:04
  • What is your main thread doing? You need to give more details on the work done. For example if your work is reading a big file then parallelizing it will make it worse. – Raam Nov 16 '12 at 07:05
  • 1
    It depends on what your tasks do - if they are mostly CPU intensive, then adding threads will help. If the bottleneck is reading data from a file it won't. See this rule of thumb to get an idea: http://stackoverflow.com/a/2193349/829571 – assylias Nov 16 '12 at 07:06
  • @Adrian Shum: Good one.. works bothways. – Raam Nov 16 '12 at 07:06
  • I'm working on a file, reading and writing on a file –  Nov 16 '12 at 07:29

1 Answers1

3

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:

  • If you're reading input data from a slow resource, you may be processing it as fast as you can read it anyway
  • If you're writing results to a slow resource, you may be processing it as fast as you can write the results anyway
  • If one task depends on the results of another, you may not be able to get any parallelization
  • If you've only got one CPU core, and the task is already CPU-bound, then adding more threads won't 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.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194