Welcome!

Java IoT Authors: Pat Romanski, Elizabeth White, Liz McMillan, Yeshim Deniz, Mehdi Daoudi

Related Topics: Java IoT

Java IoT: Article

Trimming the Fat from Swing

Trimming the Fat from Swing

I'm sure we've all heard it before: Java on the client is slow; Swing is slow. The reality is that Sun has made great progress in increasing the speed of Swing and Java on the client.

However, it's up to developers to demonstrate that Java has indeed improved to the point of usability and viability on the client.

To do this, the code needs to be very lean and clean. One of the original problems with GUI creation was the reliance upon Visual Development Tools to design and code the GUI. While these VDTs have come a long way in the last few years, I have found that many developers rely so heavily on the VDTs that they've gotten lazy when it comes to coding the actual functionality of the application.

The Problem
Methods are expensive in terms of execution time. The more method calls made, the slower the application will be. However, there needs to be a balance between speed of execution and good coding standards.

Swing makes a large number of method calls during its startup and execution. This is a price that has to be paid for its design model. What compounds the method calls that Swing requires is the number of method calls the average developer piles on top of Swing.

Multithreading Swing
The Swing API is considered to be single threaded and thread "unsafe." However, for a Swing GUI to be responsive, some actions must be threaded, such as database access.

In a normal GUI construction, if a call to a database is made, the GUI will just sit there waiting for the database access to return. Not only will the GUI be unresponsive, it won't even repaint! This can cause the user to believe the application has locked up or failed in some way. This problem is not unique to Java. Every GUI API has to deal with this same issue in some fashion. It's unfortunate that many Java Swing developers don't handle this type of situation properly.

Steve Wilson of Sun Microsystems is quoted as saying that in any situation where it's known that the process is going to take a long time, a GUI should respond to the user in some fashion within 50 milliseconds. Any slower than this and it will feel sluggish. Naturally a database request is not going to return in 50 milliseconds or less! This is where multithreading comes into play. The problem lies in properly threading your Swing GUI application to avoid complications with Swing's single-threaded nature.

The solution to this problem lies within two methods: invokeLater and invokeAndWait. These two methods were originally in the SwingUtilities class but, as of v1.2, they've been moved to the java.awt.EventQueue class. Applications can still call these methods in the SwingUtilities class but are merely wrappers for the java.awt methods.

Listing 1 demonstrates database access being spun off into a separate thread. (Listings 1-4 can be downloaded from www.sys-con.com/java/sourcec.cfm.) The method that's called is invokeAndWait, which means the worker thread is blocked until the database activity returns. However, the GUI's thread is not blocked and will allow repaints, and more. Note: This is a very primitive example designed to only show the multithreading.

Once the database call has returned, it's time to update the GUI. Since this is still in a separate thread, it won't modify the GUI directly. Thus, in Listing 1, all the GUI updating is in a call to the invokeLater method. This method doesn't block the worker thread that allows it to terminate peacefully. The work to update the GUI has been placed into the event queue, and once it reaches the top of the heap, the GUI will be updated. This allows the update to the GUI to happen from a thread outside the event thread without causing problems.

Model, View, Control
Example 1: JTable
The cleanest way to solve this problem is to write Swing code by hand as it provides two clear benefits:
1.  The code will be very lean and clean.
2.  The code will be much easier to maintain since there will be fewer method calls in the code.

For example, consider a simple JFrame with a few buttons and a table on it. Any complex GUI will generally be using GridBagLayout as its layout manager, therefore this example will be using GBL as the layout manager. Hopefully, through this example, you'll see a reduction in the lines of code, enabling you to write cleaner, tighter, and better performing GUI code.

Listing 2 shows an example GUI built using JBuilder's VDT. I'll admit I was very impressed at how compact the code was that JBuilder produced. There's very little improvement that can be done at this point. However, looking at Listing 3, you can see that we were able to remove a few method calls. The calls to setText() have been moved into the constructor calls for the buttons. The other change we can see at this point is excess construction of GridBagConstraints objects. This is excessive due to what the GridBagLayout does with these objects.

When the GridBagConstraints is passed into the GridBagLayout, the first thing that's done is it's cloned. The GridBagLayout does this so that the GridBagConstraints doesn't change on it unexpectedly. Thus, the individual creation of GridBagConstraints here is unnecessary. This is why, in Listing 4, there's only one GridBagConstraints and it's modified for each call to the JPanel's add method.

Both of these changes are relatively minor and won't improve the performance all that noticeably. However, this is where the VDT stops and the developer takes over.

It's very common for a developer to utilize the shortcuts in the creation of a JTable to populate it for data. While these shorten the development cycle slightly, they'll cost a fortune in performance. Instead, the creation of an actual table model that's customized for a specific use will improve performance. By implementing your own TableModel, you can reduce the number of method calls and object creations that are normally incurred when using the default models.

For example, take a JTable created with the (Vector, Vector) constructor. The only way you can access that data programmatically is via those vectors. However, the GUI doesn't know if anything has changed inside those vectors and therefore needs to be informed of the change so the GUI can repaint itself. However, if a custom TableModel object is created that's specifically designed to handle the data you wish to represent, you're able to add methods directly to the model that will allow you to edit the data and then fire off an event that the View will intercept and handle. This eliminates a large number of method calls and indirection in your code and indirectly increases the performance of your GUI overall.

Listing 4 is an example TableModel implementing the various methods that are required. Notice that the example extends from the AbstractTableModel. There are a few nonrequired methods in the AbstractTableModel that are useful and don't need to be replaced. This allows the AbstractTableModel to handle the listeners and deal with delivering the events that you create. This leaves us with the methods shown in Table 1.

Our example is fairly simple but it gives you an idea of how you could construct a TableModel specifically tailored to the data it will be representing. It's a rare situation indeed where you will need to display completely dynamic data.

Example 2: JTree
Another area of performance contention is the JTree API. In a large number of cases where I've seen the JTree used in a production environment, it's invariably used incorrectly, causing the number of objects involved with it to double.

The JTree API is designed around the concept of nodes; each point in the tree is either a branch or a leaf. Every point in the JTree implements the TreeNode interface. This interface defines methods inside it that tell the View whether or not that particular node is a leaf or a branch.

What happens is that developers tend to use (read overuse) the DefaultMutableTreeNode class instead of developing their own TreeNodes. This produces a "wrapper" class around their actual data that causes a doubling of the number of classes in the JTree. While this certainly works (even the tutorials from Sun do this), it's not the most efficient way to handle a JTree.

To remove this doubling of objects in the tree, one of two things can be done:
1.  Don't use any data objects inside the DefaultMutableTreeNode.
2.  Have your data objects that are going to be represented by a tree implement TreeNode.

Clearly, not putting any of your data objects in the tree is self-defeating, so we'll explore the second option - implementing the TreeNode interface. We don't need to implement the actual model since the default model expects and knows how to handle the TreeNode interface. Thus our data objects that will be displayed in the Tree need to implement the methods shown in Table 2.

None of these methods impact the data you're representing and they have very little to do with the GUI. Thus your design integrity stays intact. However, this allows you to modify the data directly, notify the model that the data has changed, and not have to go through an intermediary layer and deal with casting from Object, and so on. This eliminates numerous method calls and the creation of objects that serve very little purpose.

Conclusion
The Swing API is more complicated than other graphical APIs on the market. A large portion of this is attributed to the Model-View-Control design pattern. However, as developers we can avoid compounding the complexity of Swing by reducing the amount of code that we lay on top of it.

When you go through the optimization phase of your project, look at each method dealing with the GUI and see if there are any method calls that you can remove, any objects that are unnecessary, and any objects you can avoid creating by implementing the model interfaces yourself instead of creating wrapper objects. Once that's complete, start looking for operations that take a long time and consider putting them into separate worker threads instead of the primary GUI thread.

These simple steps will dramatically improve the performance of Swing while still adhering to the OO paradigm as well as the single-threaded rules.

References

  • The Swing Connection: http://java.sun.com/products/jfc/tsc/
  • Java Platform Performance: Strategies and Tactics: http://developer.java.sun.com/ developer/Books/performance/
  • Christmas Tree Applications: http://java.sun.com/products/jfc/tsc/ articles/ChristmasTree/
  • More Stories By Marcus Zarra

    Marcus Zarra began developing professionally in 1985 for school systems and later for legal firms in Phoenix, Arizona. He has been a Java developer since 1996 working in the industries of banking,
    telecommunications and insurance. Currently he is director of technology at Extraquest Corporation in Denver, Colorado.

    Comments (4)

    Share your thoughts on this story.

    Add your comment
    You must be signed in to add a comment. Sign-in | Register

    In accordance with our Comment Policy, we encourage comments that are on topic, relevant and to-the-point. We will remove comments that include profanity, personal attacks, racial slurs, threats of violence, or other inappropriate material that violates our Terms and Conditions, and will block users who make repeated violations. We ask all readers to expect diversity of opinion and to treat one another with dignity and respect.


    IoT & Smart Cities Stories
    The platform combines the strengths of Singtel's extensive, intelligent network capabilities with Microsoft's cloud expertise to create a unique solution that sets new standards for IoT applications," said Mr Diomedes Kastanis, Head of IoT at Singtel. "Our solution provides speed, transparency and flexibility, paving the way for a more pervasive use of IoT to accelerate enterprises' digitalisation efforts. AI-powered intelligent connectivity over Microsoft Azure will be the fastest connected pat...
    There are many examples of disruption in consumer space – Uber disrupting the cab industry, Airbnb disrupting the hospitality industry and so on; but have you wondered who is disrupting support and operations? AISERA helps make businesses and customers successful by offering consumer-like user experience for support and operations. We have built the world’s first AI-driven IT / HR / Cloud / Customer Support and Operations solution.
    Codete accelerates their clients growth through technological expertise and experience. Codite team works with organizations to meet the challenges that digitalization presents. Their clients include digital start-ups as well as established enterprises in the IT industry. To stay competitive in a highly innovative IT industry, strong R&D departments and bold spin-off initiatives is a must. Codete Data Science and Software Architects teams help corporate clients to stay up to date with the mod...
    At CloudEXPO Silicon Valley, June 24-26, 2019, Digital Transformation (DX) is a major focus with expanded DevOpsSUMMIT and FinTechEXPO programs within the DXWorldEXPO agenda. Successful transformation requires a laser focus on being data-driven and on using all the tools available that enable transformation if they plan to survive over the long term. A total of 88% of Fortune 500 companies from a generation ago are now out of business. Only 12% still survive. Similar percentages are found throug...
    Druva is the global leader in Cloud Data Protection and Management, delivering the industry's first data management-as-a-service solution that aggregates data from endpoints, servers and cloud applications and leverages the public cloud to offer a single pane of glass to enable data protection, governance and intelligence-dramatically increasing the availability and visibility of business critical information, while reducing the risk, cost and complexity of managing and protecting it. Druva's...
    BMC has unmatched experience in IT management, supporting 92 of the Forbes Global 100, and earning recognition as an ITSM Gartner Magic Quadrant Leader for five years running. Our solutions offer speed, agility, and efficiency to tackle business challenges in the areas of service management, automation, operations, and the mainframe.
    The Jevons Paradox suggests that when technological advances increase efficiency of a resource, it results in an overall increase in consumption. Writing on the increased use of coal as a result of technological improvements, 19th-century economist William Stanley Jevons found that these improvements led to the development of new ways to utilize coal. In his session at 19th Cloud Expo, Mark Thiele, Chief Strategy Officer for Apcera, compared the Jevons Paradox to modern-day enterprise IT, examin...
    With 10 simultaneous tracks, keynotes, general sessions and targeted breakout classes, @CloudEXPO and DXWorldEXPO are two of the most important technology events of the year. Since its launch over eight years ago, @CloudEXPO and DXWorldEXPO have presented a rock star faculty as well as showcased hundreds of sponsors and exhibitors! In this blog post, we provide 7 tips on how, as part of our world-class faculty, you can deliver one of the most popular sessions at our events. But before reading...
    DSR is a supplier of project management, consultancy services and IT solutions that increase effectiveness of a company's operations in the production sector. The company combines in-depth knowledge of international companies with expert knowledge utilising IT tools that support manufacturing and distribution processes. DSR ensures optimization and integration of internal processes which is necessary for companies to grow rapidly. The rapid growth is possible thanks, to specialized services an...
    At CloudEXPO Silicon Valley, June 24-26, 2019, Digital Transformation (DX) is a major focus with expanded DevOpsSUMMIT and FinTechEXPO programs within the DXWorldEXPO agenda. Successful transformation requires a laser focus on being data-driven and on using all the tools available that enable transformation if they plan to survive over the long term. A total of 88% of Fortune 500 companies from a generation ago are now out of business. Only 12% still survive. Similar percentages are found throug...