Wor White
Wor White

Reputation: 11

GUI doesn't work when synchronized method is run

I have an app with a main object (containing Swing GUI) and a supporting thread which calls on the handle() method of the object.

I noticed that when the handle() method is synchronized, while the thread is using the handle() method, the GUI on the main object are unresponsive. Code:

public synchronized void handle()){
//method code
}

i remove the synchronized keyword from handle(), the GUI is responsive even when the thread is using the handle() method.

An interesting thing to note is that when I used another object as a lock, the GUI becomes responsive again when the thread is using the handle() method. Code:

public void handle(){
    synchronized(anotherObj){
    //method code
    }
}

This suggests that Swing GUI uses methods that are synchronized. Am I right? Feel free to point me to any resources - couldn't quite find what I wanted.

Thanks.

Upvotes: 0

Views: 829

Answers (1)

Hovercraft Full Of Eels
Hovercraft Full Of Eels

Reputation: 285405

What is your "handle" method and what does it do? I believe that Swing does not use synchronization for the most part and its documentation in fact states in its API that it is not thread-safe (e.g., have a look here). Instead it uses a single thread for user interactions and program painting, the EDT or Event Dispatch Thread, and all programs that interact with Swing must respect this single thread model by calling most all Swing calls on the EDT. I suspect this is where your problem lies.

For more on Swing threading and use of background threads, please have a look here: Concurrency in Swing

Edit 1
(From my comment) I have to ask also, why this method is synchronized? Since we queue all Swing calls onto the event queue, this probably isn't necessary and is possibly harmful. A Swing program freeze almost always is due to a concurrency issue so this discussion is relevant.

You might want to make a small compilable test program (an SSCCE) that demonstrates your problem (the GUI freeze) and post it here so we can test it for ourselves.

Upvotes: 2

Related Questions