Archive for the tag: Java

Static: The Dark Side of Design

Developer's Cave 3 Comments »

Students of software must be taught early the benefits of object oriented design, lest they succumb to the dark side of static programming. When designing a software component, the temptation can be to write globally accessible public static methods in lieu of instantiable objects. Even experienced developers must remain diligent to avoid being turned to this quicker, more seductive, approach. Read the rest of this entry »

JPanel Stabilizer

Developer's Cave No Comments »

This article covers a handy bit of logic to stabilize Java/Swing components that otherwise have annoying grow/shrink behavior. The (perceived) problem occurs when a Java/Swing application uses layout managers that obey internal components’ desired sizes. The layout shifts to accommodate internal components as they grow/shrink, which can cause much distress to the end user (at least it does to me). Read the rest of this entry »

To Enum or Not to Enum

Developer's Cave, Potential RPG 3 Comments »

Java’s enum feature offers a powerful language capability: compile-time type checking of constants. In addition, enum constants make code much easier to read and debug. However, an enum represents hard-coded values, requiring application recompilation/redeployment to alter.

This conflicts with the mantra of code design taught to me: “Abstraction, abstraction, abstraction.” That is, a piece of software should be as general-purpose as possible.

Take, for example, the Potential RPG game engine. I’ve designed it to abstractly support MMORPGs, allowing game-specific content to be defined in external data files. This often precludes defining enum constants where they would otherwise make good programmatic sense.

For example, my game supports a variety of shop types (weaponsmith, alchemist, healer, etc.). Currently, these are loaded from a definition file, rather than being hard-coded in the software. Adding a new shop type can be done without modifying the code… almost (read on).

What I’ve discovered is that new content still requires logic and GUI code to be written against it. Therefore, the game must be recompiled/redeployed anyway, so why not just simplify things and hard-code enum constants?

Ideally, I’d love to make the game engine 100% abstracted from content. For example, all content-related code should be isolated into dynamically loaded classes, referenced by the content definitions. While it’s just me at the keyboard, simplification seems in order. (Unless someone is looking to invest in such a game engine…)

In summary, depending on the requirements of your project, just use enum constants unless the level of effort is worth the design/implementation/maintenance overhead. (Hmmm … now I’m talking like a software project manager.)

JFreeChart for SLOC History

Developer's Cave, Potential RPG No Comments »

While in grad school, I learned to use gnuplot to create line/bar charts. It works well for command-line scripted data processing, so long as you’re good at discerning arcane commands.

Looking for Java-based charting, I found JFreeChart. I’ve only spent a couple hours with it, but it looks to be an impressive library. It’s not simple, but appears to be well designed.

I hope to become more adept at JFreeChart. So far, I’ve only redeveloped my Potential RPG Source Lines of Code (SLOC) chart (originally processed by gnuplot):

Can anyone offer other Java-based charting library suggestions? Any opinions of JFreeChart? Read the rest of this entry »

Java “Locking assertion failure”

Developer's Cave, Potential RPG No Comments »

This article describes a Java-related assertion failure apparently due to a recent video driver update in Debian (and Ubuntu). The assertion dumps a backtrace to the console, but the Potential RPG Alpha client appears to be otherwise unaffected.

The remainder of this article describes the problem and how to work around it. Read the rest of this entry »

Surface Feature Layering

Potential RPG No Comments »

The recent significant graphic performance improvement inspired me to tinker with a few new rendering tricks. Surface features (such as trees) now stand atop the underlying terrain. Characters and creatures
can walk behind these features. The goal is to provide a more dimensional perspective to the world.

For alpha playtesters: There are some known issues with the new feature rendering, but I’ve released a new alpha version anyway.

Java Graphic Performance

Developer's Cave, Potential RPG No Comments »

I’m often amazed how much processing can be performed in a few milliseconds, even in the face of sloppy algorithms. Graphic processing, on the other hand, seems to be another story. Any excess painting can be significantly detrimental.

For the record, I’m developing this game in Linux (Debian) with no accelerated graphics drivers, and I am determined for it to run well on my platform of preference. Sun promises a vastly improved graphic pipeline with its upcoming Java update release, but this only helps with DirectX in Windows.

It’s easy to unjustly blame sluggish graphics on Java or Linux. So far in my burgeoning graphics experience, I’ve found that performance problems invariably indicate that I’ve done something horribly wrong. Reading an article on Swing animation last week inspired me to vastly improve my graphic processing.

Without getting into the technical details (unless there’s an interest), the conclusion is that Java on Linux can certainly drive graphic content, as long as you’re meticulous in your implementation. While Java’s general software performance is exceptional, only so much graphic excess can be swept under the rug.

Java Web Start: Antithesis of Usability

Developer's Cave No Comments »

Java Web Start should be a major benefit for Java application developers and, more importantly, end users. The JWS concept is simple: A configuration file (JNLP) sitting on a Web server defines how to install, update, and launch a Java application. At each launch, application resources are fetched, installed, and updated for the user as automatically as possible.

Great concept, but the reality of Sun’s JWS implementation is abysmal. End users are forced though a gauntlet of obstacles, in which any error tends to be catastrophic.

Assume JWS is installed and browser integration is configured correctly for all browsers (a MIME type must be set up to launch JWS when a JNLP file is clicked). When a JNLP is first launched, shortcuts are installed on the user’s desktop and in menus, as directed by the JNLP (barring some bugs). These shortcuts conveniently launch the application. However, there are several bugs against JWS in which these shortcuts become corrupted. The result is a cryptic error that implies the application is broken, which is enough to prevent most end users from using your application. The situation is not easily repaired (as discussed below).

One such case prompted this article (rant): Upgrading from Java 5 to Java 6 caused all JWS application shortcuts to become broken. To correct the situation, users must find the JWS Viewer application. I couldn’t find the shortcut in Windows, so had to run “javaws -viewer” on the command line. This could be a friendly viewer of installed Java applications, but is actually considered a sub-dialog of the hideous Java Control Panel, showing the JWS “application cache.” The applications had to be removed, then the original JNLP link clicked to initiate a new installation. If the user cannot perform these steps, and does not know the JNLP URL, the error is unrecoverable.

The same problem can occur in several other ways, such as renaming shortcuts, or making several JNLP changes. The end result is an error shown to the user, implying the application is broken. In all cases, JWS should be smart enough to detect the corrupted shortcut and reinstall the application. Instead, an exception and stack trace are shown to the user. This is a completely unacceptable scenario for the end user.

Another problem occurs if the user saves the actual JNLP file locally, then launches from that file. Even though the JNLP has the full URL information of the application resources, JWS does not go to the source when the JNLP is clicked locally. Thus, no updates are ever discovered, which breaks the basic contract of a so-called “online” JWS application: the user will always have the latest version.Overall, Java Web Start should be redesigned to provide a robust user experience. Otherwise, I don’t anticipate moving MMORPG out of alpha with JWS. An alternative is to simply create a launcher script (or Windows executable) that checks resources before launching the application. However, Java developers shouldn’t have to reinvent this wheel.

Resources:
This bug should never have been closed: Sun Bug 6446676
This bug appears to replace the previous: Sun Bug 6563938
Similar broken shortcut bug: Sun Bug 6549428

Swing Hangs on Thread, Old Timers to Blame, Factory Fixes

Potential RPG 2 Comments »

Elderly swing-set factory employees using thread instead of chains forces product recall?

No. Why would you think that?

This article describes how the javax.swing.Timer utility can cause your Swing application to hang at shutdown, and how to fix it.

The Timer utility is useful for repeating tasks on the Swing/AWT thread. They’re handy enough to create in many places throughout GUI code. However, each one that remains active keeps the AWT thread alive, which prevents clean application shutdown (without resorting to System.exit()). Lacing the code with Timer instances makes it difficult to track them all down and stop them when the application is supposed to exit.

To correct the situation for the MMORPG client, I created a simple factory class with a create(..) method for producing Timer instances. The factory maintains a reference to every Timer created. At application shutdown, the factory’s stop() method is called, which tells each Timer to stop(). After replacing all Timer constructor calls with the factory’s create(..) method, the MMORPG client exits cleanly.

There are a few caveats. For one, you must be certain it is safe to stop Timers in this way (a Timer may be carrying out some critical pre-shutdown operation). In general, I only use Timers for GUI-related activities, and not to drive application logic. Another weakness is that the factory cannot guarantee the Timers will not be restarted, or that more timers will not be created, after stopping the factory. This could be guarded with a more sophisticated design, such as a TimerProxy class to prevent post-shutdown starting, refusing to create new timers after shutdown, or an isStopped() method for GUI code to query.

For the MMORPG client, this simple factory pattern is sufficient to untie Timers from the AWT thread, allowing clean shutdown without resorting to System.exit().

ProxyIcon

Developer's Cave, Potential RPG No Comments »

For those who enjoy design patterns, I’ve written a ProxyIcon for the MMORPG client. The reason is to decrease memory allocation in the client, which is due in large part to graphic images, under the theory that most are not needed most of the time. This article describes the ProxyIcon (implementation details are left as an exercise for the reader). First, there is already a central factory of Icons. So, integrating a new proxy pattern only involved changing the factory. ProxyIcon implements the javax.swing.Icon interface, so users are none the wiser.

ProxyIcon knows the source of the image to load. When any Icon methods are accessed, it makes sure the internal image is loaded. If not accessed for some timeout, the internal icon can be unloaded. The simplest implementation would have set the internal Icon reference to null, allowing the garbage collector to clean it up. Why the present perfect tense? Because there’s an even better approach:

ProxyIcon holds two references to the internal Icon: A hard reference and a soft reference. After the timeout, the hard reference is set null, but the soft reference is retained. Since the embedded icon is only referenced (never exposed) from the ProxyIcon object, this leaves only the soft reference. Java cleans up soft references (only) when memory is needed. If, however, the ProxyIcon is accessed before being cleaned up, the hard reference is reinstated. This provides the best of both worlds: Application logic can set policy on when to release resources but is backed up by the Java Virtual Machine’s garbage collection logic to avoid unhelpful cleanup.

The primary benefit, of course, is that unused icon resources can be deallocated. The software design benefit is that image users do not need to concern themselves with whether the icon is currently loaded or not. Notice that all ProxyIcon references stay in memory forever (in the factory). They could also be deallocated by using soft or weak references in the factory, but the objects themselves are (theoretically) miniscule compared to image memory consumption.

Another minor benefit is lazy image loading. Instead of loading upon construction, the internal icon is loaded lazily upon first access. There are a number of icons that are requested in the code, but not always used. This feature has the benefit that the code can greedily ask for icons from the factory (e.g., as static variables) without impacting memory if not needed.

One major gotcha is that Java itself may be holding cached references to the image data, which prevents garbage collection. I have not investigated this fully, but do not use Toolkit.getImage(), as it’s API warns of just this problem. Also read the code for javax.swing.ImageIcon, which makes (undocumented) use of Toolkit.getImage(). Instead, use Toolkit.createImage() or ImageIO.read() with ImageIO.setUseCache(false). Further investigation is needed to determine exactly who has access to underlying image data depending on how it is loaded.

For Alpha testers, look at $HOME/.potentialrpg/stat/IconFactory.stat, which shows:

timestamp, total, loaded, hard_referenced, average_ms_timeout, ms_stat_time