How to limit threads in a Java QuickSort algorithm.

With the following piece of code, I quickly run into OutOfMemory exceptions, since the code starts creating Threads exponentially. However, after waiting for a long time (for all the exception texts to print out, obviously making it slower than running it with one thread only), the program eventually ends with the correct result. Is there a way to run the code as is, but making sure that no more that x threads are running at a time?

things I have tried:
- sleeping the current thread - makes it slower than one-thread.
- looping blank while Thread.activeCount() > x - doesnt work at all
- suspending resuming threads based on the activeCount - doesnt work too

Try using a thread pool. Instead of making your ThreadedSort extend Thread, make it implement Runnable. Then, instead of recursively creating new threads, recursively add runnable tasks to the thread pool.

so I finally devised a code where I get marginal performance improvement. I still cant get my mind around the fact that even with 16 threads all the improvement I get for a list size of 5000000 elements where the values can range from 0-2000000 is about 30%. I can see in the log diagram for processor activity that all 16 threads are getting involved, but not in a consistent basis (sometimes they'll all be active, sometimes only eight will be active, sometimes only one). The other thing that I noticed is that just by declaring a Thread object inside my main algorithm ( Thread thread1 = new Thread(); ), not actually starting it or using it in anyway, just by creating it - the runtime increases by 70%-100%. So the question is, when is multi-threading really applicable ??!

The number of threads that can actually execute simultaneously is limited by the number of CPUs/cores/threads in your hardware. (I'm not sure what a CPU "thread" is, but I've seen CPUs described in advertisements as "2 cores/4 threads".) If you create more threads than that, you'll probably actually decrease performance because of the extra overhead involved in switching threads in and out of the CPU. The only good reason to create more threads than your hardware can run is if your program makes more sense that way.

I wanted to add that another good reason to use threads is to keep your program responsive during blocking, slow, or unpredictable I/O. But the point is, threads are not a panacea for better performance, and often actually hurt, even when an algorithm is distributable.