-1

How do I parallelize the program on Java so that the execution time of a parallel version was (much) less than execution time of program without threads? I tried e.g. the ExecutorService ("Parallel.For" for Java?) but it works about 3 times longer

Is the problem that I use threads in Java improperly or it is unreal to get acceleration in 2 times with 2 cores (is this possible with 4 cores?)?

P.S. I need to parallelize while loop

Community
  • 1
  • 1
Bred
  • 11
  • 5
  • It's impossible to answer without seeing your code - the problem could be due to numerous reasons... – assylias Apr 14 '15 at 16:42

2 Answers2

0

Multithreading programming is useful in the following situations:

  • Multi core systems needed when intensive in memory operations (not needed if there are long I/O operations like the following)
  • Database operations (perform queries)
  • Network operations (like sending file or call a web service)
  • File operations (read write a file)

If you are not in one of the previous situations adding multithreading results in a slower application due to the overhead of switching between processes.

Davide Lorenzo MARINO
  • 26,420
  • 4
  • 39
  • 56
  • 1
    This is misleading at best: using multithreading on file operations is most likely going to be slower. And using multithreading on computationally intensive tasks should be in your list. – assylias Apr 14 '15 at 16:41
  • Using multithread in file operations like read write file is not slower. Generally multithreading is useful always when the cpu is not used at 100%. This happens often for any non in memory operation. Using multithreading for Intensive tasks in a mono core system (one cpu) is not useful. I edit my post to be more clear. – Davide Lorenzo MARINO Apr 14 '15 at 16:45
  • Re. file read write, assuming we are talking about a local hard drive, the bottleneck is the hard drive - throwing more threads at it will only slow it down.... See for example: http://stackoverflow.com/questions/8584797/multithreaded-file-copy-is-far-slower-than-a-single-thread-on-a-multicore-cpu – assylias Apr 14 '15 at 17:09
  • It depends on many factors. You can have a file read and a subsequent operation in memory and save the results to a remote db. You can do that efficiently with multithreading. Reading from a file is a slow operation so if you have a long operation to do in memory you can use the time needed to read the data from the file to elaborate the data already read before. – Davide Lorenzo MARINO Apr 14 '15 at 17:12
0

I would recommend this thread to you, since it goes into pretty good detail on the subject: [Java 8's streams: why parallel stream is slower?

The long and short of it, parallelism introduces overhead and complexity to any process, and while there are certainly gains to be had by parallelization, it won't work out to 2 threads on 2 cores = 2x faster.

Community
  • 1
  • 1