Applicet FrameWork: Note on Applet shared memory and persistence

(applies to plain Applet as well)

You might not have thought of this, but it is quite trivial to run multiple Applicets (of the same or different Applicet subclass) simultaneously in the same JVM. All you have to do is create them and invoke runAsApplication() on them from within the same main(String[]) method or one of it's callees. Running in the same JVM, these Applicets can intercommunicate quite easily.

Applet's running in browsers also have a form of memory sharing and persistence: any static field in an Applet or in one of the classes it loads, will persist over the runtime environment until the class is unloaded (probably for reclaiming memory). A runtime environment may be defined as codebase + qualified classname. Prior to unloading a class, the browser JVM will call it's method static void classFinalize(), if implemented.

According Netscape documentation, loaded classes will get reused whenever the following conditions are met:

  1. the CODEBASE attributes in the applet tags match, and
  2. the ARCHIVE attributes in the applet tags match, and
  3. the MAYSCRIPT attributes in the applet tags match, and
  4. either MAYSCRIPT is false, or the applets are on the same page.
The CODEBASE and ARCHIVE attributes must match so that we're assured that the correct version of a class gets used, even if it can be found with the same package and class name via some other class loader. The MAYSCRIPT attribute specifies that the applet is permitted to call JavaScript, and that the author of the web page trusts it to do so. Since JavaScript's security checks center around which page the script comes from, any JavaScript code called from a shared class loader would not be able to determine the correct page or perform a meaningful check. Consequently, class loaders are not shared even for the same codebase and archive file if MAYSCRIPT is enabled.

What does this mean? Applets can communicate with each other even when they are not on the same Web page. When the user runs Applets from the same CODEBASE etc. on 2 or more different HTML docs, simultaneously, consecutively, or intermittently, the static fields are not be reset, i.e. their values are shared/used persistently. This also means that you could take along some user data (e.g. search terms, active scripting, surfing path, shopping basket) across different HTML docs, without resorting to cookies or server-side programming! There is one problem that might apply if you are doing something that requires applets to stay active after the user moves on from the applet's page: pruning. Under certain circumstances (such as when the browser's in-memory cache is full) the browser will forcibly destroy and unload applet classes. Each browser will probably have a different pruning policy. There's nothing you can do to avoid it, but you can take action when it happens by overriding Applet.destroy().