Java: Swing Libraries & Thread Safety

后端 未结 11 2215
后悔当初
后悔当初 2020-11-28 05:27

I\'ve often heard criticism of the lack of thread safety in the Swing libraries. Yet, I am not sure as to what I would be doing in my own code with could cause issues:

相关标签:
11条回答
  • 2020-11-28 05:56

    It's not just that Swing is not thread-safe (not much is), but it's thread-hostile. If you start doing Swing stuff on a single thread (other than the EDT), then when in cases where Swing switches to the EDT (not documented) there may well be thread-safety issues. Even Swing text which aims to be thread-safe, isn't usefully thread-safe (for instance, to append to a document you first need to find the length, which might change before the insert).

    So, do all Swing manipulations on the EDT. Note the EDT is not the thread the main is called on, so start your (simple) Swing applications like this boilerplate:

    class MyApp {
        public static void main(String[] args) {
            java.awt.EventQueue.invokeLater(new Runnable() { public void run() {
                runEDT();
            }});
        }
        private static void runEDT() {
            assert java.awt.EventQueue.isDispatchThread();
            ...
    
    0 讨论(0)
  • 2020-11-28 05:58

    Here's a pattern for makng swing thread-freindly.

    Sublass Action (MyAction) and make it's doAction threaded. Make the constructor take a String NAME.

    Give it an abstract actionImpl() method.

    Let it look like.. (pseudocode warning!)

    doAction(){
    new Thread(){
       public void run(){
        //kick off thread to do actionImpl().
           actionImpl();
           MyAction.this.interrupt();
       }.start();  // use a worker pool if you care about garbage.
    try {
    sleep(300);
    Go to a busy cursor
    sleep(600);
    Show a busy dialog(Name) // name comes in handy here
    } catch( interrupted exception){
      show normal cursor
    }
    

    You can record the time taken for the task, and next time, your dialog can show a decent estimate.

    If you want to be really nice, do the sleeping in another worker thread too.

    0 讨论(0)
  • 2020-11-28 06:03

    Note that not even the model interfaces are thread safe. The size and the content are queried with separate get methods and so there is no way of synchronizing those.

    Updating the state of the model from another thread allows for it to at least paint a situation where size is still bigger (table row is still in place), but the content is no longer there.

    Updating state of the model always in EDT avoids these.

    0 讨论(0)
  • 2020-11-28 06:04

    For more details about threading, Taming Java Threads by Allen Holub is an older book but a great read.

    Holub, really promotes responsive UI and details examples and how to alleviate problems.

    http://www.amazon.com/Taming-Java-Threads-Allen-Holub/dp/1893115100 http://www.holub.com/software/taming.java.threads.html

    Love the "If i was king" section in the end there.

    0 讨论(0)
  • 2020-11-28 06:06

    The phrase 'thread-unsafe' sounds like there is something inherently bad (you know... 'safe' - good; 'unsafe' - bad). The reality is that thread safety comes at a cost - threadsafe objects are often way more complex to implement (and Swing is complex enough even as it is.)

    Also, thread-safety is achieved either using locking (slow) or compare-and-swap (complex) strategies. Given that the GUI interfaces with humans, which tend to be unpredictable and difficult to synchronize, many toolkits have decided to channel all events through a single event pump. This is true for Windows, Swing, SWT, GTK and probably others. Actually I don't know a single GUI toolkit which is truly thread-safe (meaning that you can manipulate its objects' internal state from any thread).

    What is usually done instead is that the GUIs provide a way to cope with the thread-unsafety. As others noted, Swing has always provided the somewhat simplistic SwingUtilities.invokeLater(). Java 6 includes the excellent SwingWorker (available for previous versions from Swinglabs.org). There are also third party libraries like Foxtrot for managing threads in Swing context.

    The notoriety of Swing is because the designers have taken light handed approach of assuming that the developer will do the right thing and not stall the EDT or modify components from outside the EDT. They have stated their threading policy loud and clear and it's up to the developers to follow it.

    It's trivial to make each swing API to post a job to the EDT for each property-set, invalidate, etc., which would make it threadsafe, but at the cost of massive slowdowns. You can even do it yourself using AOP. For comparison, SWT throws exceptions when a component is accessed from a wrong thread.

    0 讨论(0)
提交回复
热议问题