Win a copy of Murach's Python Programming this week in the Jython/Python forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Thread Pool  RSS feed

 
Priya Vasudevan
Greenhorn
Posts: 17
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hello,
Could someone tell me the advantages of using a Thread Pool??
I also need the code for Thread pool and a sample of how it is used...
Thanks!!
 
David Weitzman
Ranch Hand
Posts: 1365
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You can find a thread pool in Doug Lea's util.concurrent packages. There's also one in the Jakarta Commons sandbox. There are plenty more scattered in random places and random projects of all kinds.
The idea is that creating a thread isn't just a matter of allocating a few bytes of memory. Threads need their own stacks, among other things, and may have various other implementation-dependent resources they need to aquire or services they need to register with. Also, running thousands of threads concurrently can be extremely slow under a run-of-the-mill threads implementation. Stick on the cost of garbage collecting and it quickly becomes apparent that creating a new thread every time you need a thread can be a very bad idea if you need a thread several hundred times or more every few seconds. The thread pool gets around this problem by delaying some of your tasks for a bit until others complete and then reusing the leftover threads. Instead of allocating a thousand seperate stacks and then deleting them, you can just reuse 8 of them over and over.
One thing to note is that long-running jobs can hog all the threads in the pool. This can raise issues in certain types of applications, but it's usually not a problem.
 
David Weitzman
Ranch Hand
Posts: 1365
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
As for a sample use, a common one is a webserver. A webserver might keep a pool of 100 threads so that a few thousand people can't connect simultanously and bring down the server. If 500 people try to access the server simultaniously 400 of them will experience a slight delay, but everyone will get their requested page eventually.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!