I would like to load a file into my application. The problem I'm having is that the file could take an infinite amount of time to load.
I would like to allow the user to cancel a file if they would like to stop it loading into the system. After the file has stopped loading I would like to execute code straight after in the same thread.
I wrote out a simplified example for how this could be done. My solution is by having a nested thread for the code that could load indefinitely. If the user cancels then it interrupts the thread.
public class InfiniteLoopTest {
public static void main(String args[]) throws InterruptedException
{
final Thread[] innerThread = new Thread[1];
final Thread outerThread = new Thread(new Runnable(){
@Override
public void run() {
innerThread[0] = new Thread(new Runnable()
{
@Override
public void run()
{
try
{
// Load in the file here (Never finishes)
loadFile();
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
});
innerThread[0].start();
// Wait for the thread to complete
try
{
innerThread[0].join();
}
catch (InterruptedException e)
{
e.printStackTrace();
}
// Code that must always be called whether the file isn't loaded or not
System.out.println("Do something after loading the file");
}
});
outerThread.start();
// Wait 5 seconds then simulate the user cancelling loading the file
Thread.sleep(5000);
innerThread[0].interrupt();
}
}
The problem I'm having is I would like to use executor services instead of only threads and pass exceptions up if there are any issues. This means that although this solution works it will end up getting quite messy and less maintainable.
Is it possible to avoid a nested thread?