Languages - DevSource
DevSource: Microsoft Developer Resource DevSource Home Sponsored by Microsoft Home Add Ons Architecture Languages Techniques Using VS Forums
Home arrow Languages arrow Page 3 - What's Wrong with This Code? Java Swing and Threading
What's Wrong with This Code? Java Swing and Threading
By Marcus Zarra

Rate This Article: Add This Article To:

What's Wrong with This Code? Java Swing and Threading - ' Thread Blocking'
( Page 3 of 5 )

: The Answers">

Thread Blocking: The Answers

This is a relatively simple problem, but it is unbelievably common. The answer is: There is non-GUI work occurring in the event thread.

ADVERTISEMENT

What does this mean? The long answer is, naturally, more complicated. Swing is a single threaded model. Everything that occurs in relation to the GUI happens in a single thread. When you click a button, that event is fired in the event thread. This same thread is responsible for drawing the GUI. Therefore, in the example above, my button action causes a very large problem.

To test this problem, run the application as it is shown. Once the GUI is displayed, resize it a bit, so that the center square is larger and easier to see. Next, hit the activate button. This button is designed to have a very large delay — simulating database activity, or some other lengthy back end process. Once you push the button, go ahead and resize the window again.

Notice anything different? The center no longer resizes to match the window size! In fact, you can't do anything with this window that requires the window's code to respond. Depending on your operating system, you might be able to keep the window redrawing correctly, but you cannot close the window, nor can you get any of the GUI components to resize properly.

Because the simulated database activity is occurring inside of the event thread, that thread is busy, and cannot process the other events that are flowing into it. When you resize the window, an event is sent — but that event is sitting in the stack waiting for the database activity to complete before it can be processed. The same goes for a window closing event, and every other GUI event that is not explicitly handled by the operating system.

Naturally, this is a bad design. The way to solve this is actually very simple and takes just a small amount of extra code.

The correct way to handle this is to execute the simulated database code inside of a separate thread. Thankfully, threading is very simple in Java. Below, I have reworked the action listener to spin off a separate thread to handle the database code.

  private void initListeners() {
    btnActivate.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent event) {
        DatabaseSimulator ds = new DatabaseSimulator();
        ds.start();
      }
    });
  }

To make this method as clean and maintainable as possible, I moved the database handling code into its own separate inner class, as follows:

  class DatabaseSimulator extends Thread {
    public void run() {
      //Simulate database access
      System.out.println("Starting simulated database access");
      try {
        Thread.sleep(100000);
      } catch (InterruptedException e) {
        e.printStackTrace();
      }
      System.out.println("Simulated database access is complete");
    }
  }

Once these changes are implemented, the test class runs remarkably smoother. Now, when the button is pressed, the GUI does not delay at all. Even while the database code is running in the background, the GUI is fully responsive and can receive input from the user.

This code change introduced a second error, however. If you click on the activate button more than once, multiple database threads are spawned and start running. One way to prevent this from happening is to disable the activate button after it has been pressed, and reactivate it after the database code is complete. In the next section, I will detail the safest way to do this.



 
 
>>> More Languages Articles          >>> More By Marcus Zarra
 



Microsoft's Future: A Chat With Their CTO, Barry Briggs

Play Video >

All Videos >

Julia explores the Robotics Studio!

Read now >

Messages to Bill Gates!

Read now >

View Now
DevSource RSS FEEDS
XML Want an easy way to keep up with breaking tech news? And the Get DevSource headlines delivered to your desktop with RSS.