• Post Reply Bookmark Topic Watch Topic
  • New Topic

How Do Thread Pools Work?  RSS feed

 
Anthony Watson
Ranch Hand
Posts: 327
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Can worker threads return to the pool after processing a request? I thought that once a thread is done, it can't be started again. Can someone please explain how thread pools work?
 
Dan Chisholm
Ranch Hand
Posts: 1865
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Anthony,

You are correct. A thread that runs to completion can not be restarted. You can work around that problem by not allowing the run method to run to completion. In other words, the run method would contain an infinite loop.

I'm sure that google will help you find numerous articles and/or tutorials on Java thread pools.
 
Stan James
(instanceof Sidekick)
Ranch Hand
Posts: 8791
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The Apache Commons Thread Pool is dead simple and should provide fun reading. The heart is a blocking queue. When you ask for an item from the queue and the queue is empty, it blocks - makes you wait - until somebody puts an item into the queue. You can start up any number of threads that are trying to get commands from the queue. When they get one they call an "execute" method on the command and then go back for another. So the execute methods run on the threads. Neat. If commands are coming in faster than we can handle them the queue gets bigger. If the commands slow down the queue will get smaller and maybe empty.

Look at Timer for examples of making commands (TimerTasks) run on other threads.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!