I wanted to see how much time difference would it make to use a multi-threaded producer instead of a single threaded one. I setup an ActiveMQ on my local machine, wrote a pr
Multithreading can be slower than threading for a few reasons. One is that the CPU of the computer is a finite number and thus can't run all the threads at the same time making it slower. Another is that you also have a finite amount of memory causing the thread to take longer since it takes more memory.
Think about multithreading in this way, you have a hallway that can fit 3 at a time optimally. If you have less people going through that hallway at once then it will take longer to get all the people through it. Also, oppositely if you try putting too many people through it at once the hallway to get clogged up and it will be hard for anyone to get through.
This is how multithreading can be bad here and also in some other cases.
--------------------------------------EDIT OF WHAT IS HAPPENING:----------------------------------------------------
You said in your problem that you would divide 3M by 8 for you single threaded program so that it would send no more than 375000 messages. But when you multithreaded you sent all 3M instead of just 375000? If this is true than the reason multithreading is slower than single threading is because java can't perform different threads at the EXACT same time, it looks like its performing at the same time because of the speed its running, but it really is switching between all the thread you have set up. And it DOES take a small bit of time to switch between it. A few nanoseconds, therefore it would take longer since even though each thread in the multithread is running the same amount in the single thread, it needs to switch between threads that make it take that ever so small amount of time that add up to the 8 seconds extra that it took to run.