• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Control number of threads

 
Greenhorn
Posts: 16
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I've been wondering how to do something like this for a while . . .

Lets say you have a program that polls a directory that has files to "process" (lets say, pick up a file, parse it and do something with it. Doesn't matter really)

There could be a large number of files there to process. Each file takes a bit of work to do so processing them single-threaded could take too long.

Each file to process takes a fairly significant amount of work and there could be many files - So you wouldn't want to go ahead and create one thread for each file there. You could end up with Hundreds of threads all doing lots of work, possibly run out of memory or bring everything to a grinding halt.

Ultimately, you'd want to have some kind of limit for a maximum number of files you want to process simultaneously. Lets say you had a properties file or something for your program where you could set the MaxThreads to be 5 or 10 or whatever seemed appropriate.

What would be a good strategy to use to develop a "Thread Controller" of sorts that would respect the Max Threads and would spawn that number of threads maximum? Then when one of the threads dies it can go ahead and spawn a new one until all the work is done.
 
(instanceof Sidekick)
Posts: 8791
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Java5 has such a thing. See the Executor interface and the Executors factory that creates different kinds of thread pools. You usually put tasks to be executed into a queue and the thread pool pulls them out and executes them. I think you're looking for a fixed size pool or one with a growth limit.

If you're working with an older JRE look for the Doug Lea concurrency package or the much simpler Apache Commons ThreadPool. Reading the commons code is a good education - the heart of it all is a blocking queue.
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
reply
    Bookmark Topic Watch Topic
  • New Topic