by John D. Mitchell

Java Tip 9: More on threads, Netscape, and the resize problem

how-to
May 1, 19963 mins

Continued discussion of how to deal with applet resizing in Netscape Navigator

shutterstock 560673883 coffee poured into white coffee cup coffee beans java
Credit: jazz3311 / Shutterstock

We discuss further the interaction of threads and resizing. Last time we presented Noah Greenโ€™s take on how to deal with threads in the face of Netscape Navigatorโ€™s resizing behavior.

A couple of readers suggested a different approach with different tradeoffs that may work better for you.

Quick recap of of the problem: Netscape calls the appletโ€™s stop() method before calling both resize() methods and then calls the start() method. Noahโ€™s solution was to suspend() the threads in the stop() method and to then resume() in the start() method. He then goes on to do a bunch of stuff to terminate the threads after a timed delay.

There are really two separate concerns here. The first issue is whether or not to suspend() or stop() threads in the applet stop() method. The second issue is where/how to actually kill the threads.

Bill Day takes the stop and creates a new approach in his VisAnimator applet (which is based on Sunโ€™s Animator). This approach works fine for Bill since his threadโ€™s important state information is actually kept inside his Applet object. Restarting the display of the graphics afresh rather than continuing from where the program left off is no big deal in this case. Since his stop() is killing the threads, nothing special need be done when the applet is closed/killed/etc.

Billโ€™s approach is fine for very simple threads, but termination is a bit too ruthless for complex ones. For example, you wouldnโ€™t want to kill a thread that is off doing some database work just because of a resize. Clearly, suspending and resuming threads is much better in this case.

As Noah noted, there is still the issue of getting rid of the threads when the applet is closed. The simplest solution is to nuke the threads in the appletโ€™s destroy() method. No muss, no fuss. Another reason to use the suspend/resume method is that it is more efficient to suspend threads and then later resume them than it is to stop them and create new threads. The old thread is now garbage and so the garbage collector has more work to do. Access to any state information external to the thread must be properly synchronized, further increasing overhead.

Subsisting on caffeine, sugar, and too little sleep, John D. Mitchell has been consulting for most of the last nine years, and developed PDA software in OO assembly language at Geoworks. He funds his Java addiction by writing compilers, Tcl/Tk, C++, and Java systems. He co-authored the hot new Java book Making Sense of Java and is currently developing a Java compiler.