• Post Reply Bookmark Topic Watch Topic
  • New Topic

Thread.activeCount() problem  RSS feed

 
Brendan Nolan
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have a situation where I need to limit the number of Threads to five. A function is make asynchronous recursive calls to itself. If the number of Threads would exceed five the call is instead made synchronously.

if(Thread.activeCount() == 5) {
call function synchronously
} else {
call function asynchronously
}

My problem is I can a situation where the number of current activeThreads is 4. They both check if the activeCount is five and then make an asynchronous call. Making the number of active threads 6.

I can't figure out away of mutual exclude the check and the call. Anyone able to point me in the right direction.
 
Brendan Nolan
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I think I figured it out myself.

If I create a semaphore and call like this

sema.acquire();
if(Thread.activeCount() == 5) {
sema.release();
// call function synchronously
} else {
// call function asynchronously
sema.release();
}

Anyone care to comment
 
Henry Wong
author
Sheriff
Posts: 23283
125
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Another option (if you are using Java 5) is to use a thread pool executor. The thread pool will maintain the number of threads -- you just submit the runnables (and callables) to it.

Take a look at the ThreadPoolExecutor class.

Henry
 
Brendan Nolan
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Henry,

It was a question from a sample exam. So the ceiling had to be 5 and using Thread pools are not an option.

I think the semaphore solution was what was being looked for.

Brendan
 
Stan James
(instanceof Sidekick)
Ranch Hand
Posts: 8791
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Interesting. If the Executor classes are banned, with BlockingQueue you could write your own thread pool in a handful of lines.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!