I have a program where I am loading a file while at the same time I am displaying a window to inform the user that the file is being loaded. I decided to make a FileLoader class that was a SwingWorker which actually handled loading the file and a ProgressWindow that implements PropertyChangeListener to inform the user about the status of the SwingWorker that was passed into it.
My code currently looks like this:
FileLoader loader = new FileLoader(filePath);
new ProgressWindow(loader, "Loading File", "Loading File");
//ProgressWindow's constructor calls loader.execute() inherited from SwingWorker
doc = loader.getFile();
The problem is that I'm having a race condition. ProgressWindow gets constructed, which calls loader.execute(), which then runs its stuff until the task is done. I was expecting that all to complete before the code above continues to run, but instead it keeps going while the loader's execute method is running, resulting in a race condition.
I've tried reading the Java synchronization stuff, but I'm having a hard time making sense of it. All I want to do is wait until the FileLoader's isDone() method returns true, then continue on with the loader.getFile() line. Is there an easy way to do it? Or for that matter, is that the best way to do it?
Alright, well I found the answer to my original problem, even if another problem came up. I figured out that I can change from SwingWorker<Void,Void>
to SwingWorker<File,File>
and then use the built in get() method to return the File (which automatically waits until the Swingworker is done). This solves my concurrency issues. However, the GUI wound up getting locked up in the process, but that seems like another issue.