Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 433
Sergey Karpushin Avatar asked Jan 28 '26 18:01

Sergey Karpushin


2 Answers

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

Hope this helps...

like image 200
px3j Avatar answered Jan 30 '26 08:01

px3j


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.

like image 42
Cameron Skinner Avatar answered Jan 30 '26 09:01

Cameron Skinner



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!