Monday, February 18, 2008

Play Safe with Swing

Last month, I was writing a GUI based code in Java. As Swing provides rich UI so I decided to go for Swing. Here is a simple piece of Suggestion, which most of us know already. If you are a novice in Swing, you always need to take care in calling UI work. Reason is simple, swing is not thread-safe and calling GUI work randomly will lead to a deadlock in code. We are seeing 'n' no. of problem with Swing code, just because developers don't know(or maybe forget) that swing is not a thread-safe world. Sometime you are not able to see the problem initially but afterward when your code is going heavier and heavier you will face lot of problems.

How to make Swing Thread-safe ?

Its not a tough job. First see this, this is more or less like a rule and you can apply anywhere to write a safe code:

public static void main(String[] args) {
JFrame frame = new JFrame();
frame.show();
// Anything after this is going to be crappy and thread unsafe
}

If you are going to write two UI work, and since things are not synchronized, you can go into a big mess. I wanted to post my code where I got the problem some days back, but its too big to post. No worries I got a code from here which is amazing ! You know what is cool, it crashes every time :)

import javax.swing.*;
import java.awt.*;

public class StrangeProblem extends JFrame {
static {
new StrangeProblem();
}

private static void staticMethod() {
System.out.println("This is never reached");
}

private StrangeProblem() {
getContentPane().add(new MyJDesktopPane());
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(300, 300);
setVisible(true);
// If commented out, program works fine, otherwise it hangs
new JInternalFrame();
}

private class MyJDesktopPane extends JDesktopPane {
protected void paintComponent(Graphics g) {
super.paintComponent(g);
System.out.println("We will now call the static method...");
staticMethod();
System.out.println("Static method was called.");
}
}

public static void main(String[] args) {
}
}

(Thanks for the poster of this code)



So now you got the thumb rule, what not to do ! Alright time to see what to do.

Simple. Run your code in the event-dispatching thread. Most of the UI like event, mouse clicks are always handled by event-dispatching thread. SwingUtilities class provide two methods invokeLater() and invokeAndWait() to get rid of this problem. Now, why two different methods is a big mystery, but use invokeLater() if its a case of Swing. So, now the code skeleton is :

public static void main(String[] args) {

SwingUtilities.invokeLater(new Runnable() {
public void run() {
JFrame f = new JFrame();
f.show();
// you can write more UI work here
}
});
}

I can leave it on to you to make the above code deadlock free :). For more detail, see the SwingUtilities class JavaDoc.

No comments: