Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>A better solution would be something like this:</p> <pre><code>public class Whatever { private String text; private final Object TEXT_LOCK = new Object(); public void setText(final String newText) { synchronized (TEXT_LOCK) { text = newText; } SwingUtilities.invokeLater(new Runnable() { public void run() { someLabel.setText(newText); } }); } public String getText() { synchronized (TEXT_LOCK) { return text; } } } </code></pre> <p>This will ensure that if two threads try to call <code>setText</code> concurrently then they will not clobber each other. The first thread in will set the value of <code>text</code> and enqueue a UI update with that value. The second thread will also set the value of <code>text</code> and enqueue a second UI update.</p> <p>The end result is that the UI will eventually show the most recent text value, but the internal <code>text</code> variable will <strong>immediately</strong> contain the most recent value.</p> <p>A couple of notes:</p> <ol> <li>Using a seperate lock object (i.e. <code>TEXT_LOCK</code>) means you are not vulnerable to code somewhere else locking the monitor on the <code>Whatever</code> instance and inadvertently causing a deadlock. Best to always keep tight control of your lock objects. It's also best to minimize the size of your synchronized blocks.</li> <li>You <em>could</em> make the whole <code>setText</code> method synchronized, subject to the caveat that it does make you potentially vulnerable to deadlock as above.</li> <li>Reading the value of <code>text</code> also needs to be synchronized even though <code>Strings</code> are immutable. There are subtleties to the Java memory model that mean you <em>always</em> need to synchronize around variables that can be read/written by multiple threads.</li> </ol> <p>Check out Brian Goetz's <a href="http://rads.stackoverflow.com/amzn/click/0321349601" rel="noreferrer">Java Concurrency in Practice</a> for a great dive into the tricky parts of concurrency (including the memory model weirdness).</p>
 

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