Q:

What is the best way to limit number of threads running specific method?

Situation

I have web application
I have class which does complicated mathematics computation
Equations can take place from time to time depending on what request is
Sometimes many threads starts this computation simultaneously
When too many computations started, computer is become hanged (completely freeze = 99 CPU usage)

My goal is
My goal is to avoid hanging/freezing. 
My guess is that it could be done by limiting number of simultaneous computations (probably to NUMBER_OF_CPU_CORES - 1)
Question is
What is the best way to reach this goal?
I know that there is java.util.concurrent.Semaphore, but maybe there is better approach?

A:

Take a look at the Java ThreadPoolExecutor  This should help with what you are trying to do.
Hope this helps...

A:

Semaphore looks like it is exactly what you want.
You'll probably want to put some logic in so that you use Semaphore.tryAcquire and return an error to the user if it cannot acquire a permit. If you use the blocking acquire method then you'll still wind up with a locked-up server.

