I am writing a program that copies files from A to B. Due to ouside constraints, we cannot copy all files at once or can use any java file copying mechanism (contraints like copy with different dates, use files rights of goal directory, etc.).
Instead, we have to use robocopy as a command line tool for each file individually and then write a report for each file if copying was a success or a failure. If the robocopy call takes too long, we kill the process that runs it, which throws a InterruptedException that needs to be handled.
We use a ProcessBuilder to create a Process Object.
Here, the waitFor(timoutTime, timeUnit) call throws the InterruptedException(), since it interrupts the process once time ran out.
// Wait for the process to complete
if (!process.waitFor(timeoutTime, timeUnit)) {
// If time has passed, kill it.
process.destroy();
// If it is not killed in 1 minute again with more force.
process.waitFor(1, TimeUnit.MINUTES);
process.destroyForcibly();
}
Even though we call a new process for copying, we want to have a single-threaded like performance, where each File is copyied one after another. This is by choice and should remain that way.
Since we want the loop to finish, the first idea was to catch the Exception, write an error report and deal with the next file.
However this is bad prectice and Sonar recommends either rethrowing the Exception or interrupting the curren Thread.
Problem is:
- We do not want to interupt the current thread, only the process, which is already killed. The current Thread should keep on running until all files are worked through, so it can return a report like this:
- File A success
- File B failure
- File C sucess
…
- Re-throwing the failure will also abort the loop. A Idea I had was to consume the Exception, set a flag and after all is done, re-throw it, but this also does not comply with best prectice.
So here is the question:
How do I handle InterruptedException in an application that needs to perform multiple action that can throw the Exception after one another, but need to perform each action?