I am working on a project where one thread forks 4 other threads and waits for their completion. The forking thread should have the ability to stop the forked threads at any time.
To, accomplish the same, I did something as such:
class ForkedThread implements Runnable {
public boolean keepRunning = true;
public void run() {
while(keepRunning is true ){
//Do the Job
}
}
}
Now since keepRunnig is public, it can accessed from outside and can be made false.
My Question is will I have to synchronize the usage of keepRunning or its fine.
Secondly, is this technique OK. Or shall I use a ThreadPool to do my job.
Actually, using ThreadPool will increase the complexity of my code, which I didn’t wanted. Please help.
Simply declare keepRunning as volatile, i.e.
and you’ll be fine. The volatile tells Java that the variable will be accessed by multiple threads and should be made thread-safe. This is not really a big issue with booleans, but becomes important with references and longs.
The technique you’re using is good practice. It allows for graceful termination of the threads in question. I would recommend you look at the new concurrency libraries (i.e. ExecutorService) of Java as they makes things like you’re doing easier and safer as well. Well worth the investment!