I wrote a simple threadpool that's been working very well for me. However, my program would never exit since I have child threads and run. I usually run 10 threads at a time, with about 2000 tasks to perform. After all the tasks have been executed, the active threads would never exit. Anyway I can work around it?
My understanding is daemon thread would just exit after execution completed. But the scenario for me is that I don't know how many worker objects I would add. So I initialize the pool with 10, but I could be adding 100 to it. So daemon thread would just execute the first 10 and then exit, leaving other 90 not running. Is my view correct?
author and iconoclast
By definition, the JVM will exit when the only running threads are "daemon" threads. Having a single non-daemon thread still running will keep the application alive. So whichever thread either has the list of work, or receives the requests for work, should be a non-daemon thread, and it gets to decide when the application should exit by terminating itself. Am I missing something?
Joined: Oct 02, 2000
Here is my basic design: I have a thread pool, it basically maintains the threadpool. I have a worker thread, and does the execute, calling run method etc. The thread pool uses a simple ArrayList to keep a list of available threads. When pool.addWork(Runnable) is called, and hands it off to WorkerThread, which add itself to ArrayList workingList and does the work. My worker thread essentially runs if there is work to be done, and waits until there is more work. This is the part I get stuck on, like my previous post states, I don't know how many tasks I need to add, or the time lapse between the adding. I understand I need to figure out a wait to break out of the wait() state with interrupt which I can do thru thread pool class. I just don't know when I should invoke it. Also, I would like to make it self-terminating, is that possible?
Is there a way that you could keep track of how many incomplete tasks there are in the system? Like with a counter that you increment every time a taks is assigned, and decremement every time a task is completed? When the count reaches zero, you could just call System.exit(0). Of course, you'd have to make sure that check isn't made until after you've started some tasks, or the system will exit before it begins. There are of course other ways to track incomplete tasks. You might have a List of tasks which have not been completed, for example. Or perhaps two - one List of tasks which had not even been started yet, and another List of tasks which were being worked on by a thread. Once both lists have size() == 0, exit.
"I'm not back." - Bill Harding, Twister
Joined: Oct 02, 2000
Actually, that's exactly what I had in mind. But how do I check is a thread is in wait state. I mean the isAlive() method doens't excatly provide that functionality.