I’m faced with a very slow data import console app and I’m trying to speed it up by multithreading it.
Is there an example pattern for starting and managing X number of worker threads in a console app? Ideally I was hoping that there would be something like:
ThreadManager tm = new ThreadManager(maxthreads=10);
while (moreWork = true) {
tm.addThread(new Thread(new MyClass));
}
The ThreadManager would add threads until the max was reached and then wait patiently until a slot became available for a new thread.
Anything like that out there? I can’t be the first one that’s faced this problem.
@jeshurun’s answer is correct but for posterity, I thought I’d add some more information. If you utilize the great
ExecutorServicecode then your code would turn into:Your
MyClassshould either implementRunnableorCallable. If it is aRunnablethen the thread pool will execute theMyClass.run()method when it has an available thread. Same withCallableexcept that theFuture<?>returned by thesubmit()method can be used to get the value returned by yourMyClass.call()method. You can also get any exceptions that were thrown bycall(). Here’s a decent tutorial.