set time limit on running of a thread
hi all,
I want to run a program in a new thread and stop it if it takes more time than expected, so there are two threads in my application the parent is some thing like this:
Code :
thread2.start();
while(thread2.isAlive())
{
Calendar currentCalendar = new GregorianCalendar();
currentMilliSecond = currentCalendar.get(Calendar.MILLISECOND);
if(currentMilliSecond-startMilliSecond > threadTimeLimit ||
currentCalendar.get(Calendar.SECOND) > startCalendar.get(Calendar.SECOND))
{
thread2.stop();
}
}
and the other thread (thread2) runs a simple program with infinite loop for some specific input. I observed some abnormal behavior from this application, i think some thing is wrong with birth and deaths of threads, is it safe to use this code for restricting the life time of a thread?
Thanks in advance,
Zahra
Re: set time limit on running of a thread
Read the API doc for the stop() method. Its all there.
The stop() method is depreciated and NOT recommended.
Recommended way is to use a flag to communicate to the thread that it is to exit.
Re: set time limit on running of a thread
Thanks for your advise but i have a limitation that is i can not change the code associated with second thread to have or check any flag because it is generated automatically and i should run for lots of automatically generated code so i need a mechanism to terminate a thread that is not aware of its status.
Re: set time limit on running of a thread
If there is no thread awareness, you cannot safely stop/suspend/resume a thread in general. Depending on your current situation, this may or may not matter (though, it sounds like from your situation you might not have this luxury and will need to safely remove any object locks that thread is holding).
If you want more information about the problems associated with stop/suspend/resume, see this page: Java Thread Primitive Depracation. They also suggest some alternatives to using these methods, but they are all similar to what we have provided as alternatives here.