Memory Management


The Java plugin (or its classloader more precisely) uses a caching mechanism for applets, holding references to all applet instances already executed.
If the applets contain internal fields the garbage collector will not be able to free these internal fields when switching to another applet.
Since the plugin's heap space is shared by all applets and its size is restricted per default to 64M, an out-of-memory exception may be thrown when starting multiple applets consecutively (the number of applet starts depends on the memory usage of the applets).
For this reason applications with a high memory consuption should be delivered as WebStart applications rather than as applets.

For applets, there are basically two possiblities for releasing the heap space used by applet fields.

Automatic Memory Freeing (recommended)

The following code offers a mechanism for releasing automatically all memory in applets. It uses reflection for freeing the applet's proper fields.

In order to release unused memory, all applet fields must not be declared as final since final fields may not be changed after their initialisation.

Paste the following code into your applet:

public void destroy() {
    try { // silent failing
        Field[] fields = getClass().getDeclaredFields();
        for (int i = 0; i < fields.length; i++) {
            try {
                if(!fields[i].getType().isPrimitive() && !Modifier.isFinal(fields[i].getModifiers()))
                    fields[i].set(this, null);
            } catch (Exception e) {} // called upon private fields in super- or sub-classes
    } catch(Exception e) {}

Manual Memory Freeing

Fields may also be freed manually by implementing a destroy() method where all fields must be set to null. In addition the super implementation of this method must be called in order to release the fields of the super classes:

title = null;
anObject = null;

Add picture from clipboard (Maximum size: 500 MB)