chnging
chnging

Reputation: 775

Java multithreading performance

So I've been playing around with threads in Java and I made a test. I made a program that makes around 10^9 multiplyings and then prints the milliseconds that were needed.

The program has 2 modes one of them does not print anything but just the milliseconds needed. The other mode however prints out "It's done" everytime a number is multiplied.

With the first mode the results are good with 1 thread I got result of 8270 ms and by the time I was using 8 threads I got result of 2237 ms (I'm testing on a 8 core computer).

With the second mode however the result with 1 thread was 94 054 ms and with 8 threads I got 96 430 ms.

My question is why the performance in the second mode is not better with 8 threads than with 1? I'm guessing it's something with that you can't print 2 things at the same time in the terminal so there is a que and that's the reason but that's just a guess.

Upvotes: 0

Views: 93

Answers (2)

Oliver Dain
Oliver Dain

Reputation: 9963

I'm guessing it's something with that you can't print 2 things at the same time in the terminal so there is a que and that's the reason but that's just a guess.

Yup. I don't know the specifics, and it depends on how you're printing (system.out.println vs. a logging library, etc.) but whatever you're doing, the code needs to ensure two threads aren't writing at the same time or the output would get garbled. So there must be some kind of mutex, blocking queue, etc. being used. That means as you add more threads, your not adding more parallelism (as they all block on the same mutex) but you are adding more lock contention so more threads == more slow.

Upvotes: 2

Patricia Shanahan
Patricia Shanahan

Reputation: 26185

The key analytical tool for this sort of issue is Amdahl's Law, which gives an upper bound for the speed-up due to parallelism based on the fraction of the work that is strictly serial. If n is the number of threads, B the fraction of the work that is strictly serial, and T(n) the time using n threads:

T(n) = T(1)(B + (1-B)/n)

Assuming most of the increase in time from adding the output is serial, we have B around 0.9.

T(8) = 94054(0.9 + 0.1/8)
     = 85824.275

That is a lower bound on the time. In practice, 8 threads tripping over each other fighting for the same lock can waste about as much time as 8 cooks in the same small kitchen cooking one dish.

Upvotes: 2

Related Questions