A friend told me about the following problem:
He is using the java Process class to execute a method. However, this class does not have a method that allows to terminate the execution after a timeout was reached.
A possible solution for that can be creating a thread that receives as parameters the process and a timeout value.
The thread will perform the following:
1. Check if the timeout value was reached.
2. If the timeout value is reached, the process will be destroyed.
For example:
However, this thread posses a busy wait loop inside it, which is not recommended to be used.
A better solution for that will be using the Thread.sleep method instead the busy wait loop -
And this also means that we do not need to pass the start execution time as parameter to the thread.
However, if we take a closer look, we will see that we execute the process outside the scope of the given thread, for example:
The process is executed from the main thread of the application, and the after execution, the timeout thread is executed. It is up to JVM (and the operating system) to determine when the timeout thread will be executed - so it is possible that some time will pass between the process execution and calling the Thread.sleep method in the timeout thread.
In order to overcome this problem and reach a more accurate behavior, we should do the following:
1. Measure the time right after the process was executed
2. Pass it to the timeout thread
3. Change the value passed to the call to Thread.sleep to take into consideration the time that has passed since the execution of the thread
The code of the Main class will look like this:
The code of ProcessTimeoutThread will look like this:
nice. very useful.
ReplyDelete