Image you have a method doWork() that can take several minutes to complete, you want to spawn a bunch of these from your getWorkDone() method and wait for them to complete then return. Help me to improve the following code:
[ June 16, 2007: Message edited by: Brian Spindler ]
I like Stan's suggestions here. If you want to stick with the code you've got written though, the big problem I see is here:
Both setRunning() and getRunnint() are synchronized, but that's useless here, because there's a gab between the call to getRunning() and the call to setRunning(). It's equivalent to this:
To protect against interference from other threads, you would need a synchronized block or method that contains both method calls. For example:
or more simply:
This sort of problem is common with many synchronized methods - any time you need to call two or more different synchronized methods in succession, you need to consider what happens if another thread calls a method in between those method calls. Typically the answer is to place the synchronization at a higher level than it was before.
In addition to suggestions posted by Stan and Jim.
The one thing that stands out for me is the Thread.sleep(1 * 1000);
I suggest a join(), or more preferrably CyclicBarrier as established practice. I always waste some processor cycles on checking some condition in a loop or something, considering any sort of wait() to be unreliable
"The differential equations that describe dynamic interactions of power generators are similar to that of the gravitational interplay among celestial bodies, which is chaotic in nature."
Joined: May 17, 2007
Thanks Ranchers! I think I've got enough to go on. At this point I'm leaning towards the FutureTask approach, it seems perfect for my needs. I need to submit N tasks and wait for them to finish processing before I can return the computation.
And thanks Jim for the heads up on the synchronization issues.