Note that there are some explanatory texts on larger screens.

plurals
  1. POWhy is my code not thread safe?
    text
    copied!<p>I'm creating a game where levels can be loaded from a file. This is done on a separate thread, while everything else is done on the Event Dispatch Thread.</p> <p>I tested the code by loading from a really large test file, and it turns out that the Event Dispatch Thread on occasions is unresponsive while the level is being loaded.</p> <p>I can't seem to figure out the cause. Here's some of my code:</p> <pre><code>public class LevelSelectionWrapper extends GamePanel { ... private JList list; private File[] files; ... //Lock object for synchronization private Object lock = new Object(); //Runnable for loading levels from files on a separate thread private Runnable loader = new Runnable() { @Override public void run() { synchronized(lock) { //Load levels from files List&lt;Level&gt; levels = LevelLoader.load(files); // &lt;------------- ... SwingUtilities.invokeLater(new ListUpdater()); } } }; ... private void createOpenFileButton(Container container) { final JFileChooser fc = ... ... //Create open button JButton openButton = new JButton("Open file"); openButton.setFocusable(false); openButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { int returnVal = fc.showOpenDialog(LevelSelectionWrapper.this); if(returnVal == JFileChooser.APPROVE_OPTION) { synchronized(lock) { files = fc.getSelectedFiles(); } //Load files on separate thread new Thread(loader).start(); // &lt;------------- } } }); container.add(openButton); } } </code></pre> <p>I've added two arrows to the code:</p> <ul> <li>The first one is the time consuming method (when the files are really large). On occasions, the Event Dispatch Thread is unresponsive while this code is running.</li> <li>The last one is where the runnable is invoked.</li> </ul>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload