Sergey Karpushin
Sergey Karpushin

Reputation: 874

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

Situation

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?

Upvotes: 3

Views: 4838

Answers (4)

Martin James
Martin James

Reputation: 24847

Reduce the priority of the threads calling your method. If the rest of the apps on your box are not CPU-intensive, this will hardly affect your computations but responses to keypresses etc. should still be good.

Actually, I'm surprised that the box would hang/freeze even with a CPU-overload from multiple ready threads, (unless their priority has been raised). Sluggish maybe...

Upvotes: 0

erickson
erickson

Reputation: 269637

You should probably configure your application container to be limited to the number of request threads that you desire.

Barring that, the Semaphore is the perfect tool. Use the tryAcquire() method, and be sure to put a corresponding release in a finally block, like this:

if (permits.tryAcquire(7, TimeUnit.SECONDS)) 
  try {
    /* Do your computation. */
    compute();
  } finally {
    permits.release();
  }
else 
  /* Respond with "Too busy; try later," message. */

Upvotes: 2

Cameron Skinner
Cameron Skinner

Reputation: 54276

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.

Upvotes: 2

px3j
px3j

Reputation: 236

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

Hope this helps...

Upvotes: 7

Related Questions