views:

59

answers:

2

I have a simple applet on a web page like this. (This is a test case cut down from a more complicated applet).

package test;

import java.applet.Applet;

@SuppressWarnings("serial")
public class SimpleLoopApplet extends Applet
{
    public void init()
    {
        System.out.println("SimpleLoopApplet invoked");
        try
        {
            while (true)
            {
                try
                {
                    System.out.println("Sleep for 1 second");
                    Thread.sleep(1000);
                }
                catch (InterruptedException e)
                {
                    System.out.println("Applet thread interrupted while sleeping");
                }
            }
        }
        finally {}
    }
}

On Firefox 3.6.8 on one computer this applet will run for 20 seconds and then exit abruptly, as if the VM is terminating (The java console will disappear; the Java icon will remain in the system tray until I mouse over it; the finally block is never reached).

It's consistently 20 seconds. 20 "Sleep for 1 second"s printed from the above code, if I extend the sleep to 5 seconds, then 4 messages are printed before termination.

In IE and Chrome on the same computer, the loop will continue on indefinitely, as it will in Firefox 3.6.8 on a different computer.

Can anyone suggest why the applet might terminate in this way?

+1  A: 
Can anyone suggest why the applet might terminate in this way?

I haven't found an offical reference, but it looks like a timeout for initialization. You could put your code in the start method which shouldn't have any timeouts like that.

From Javadoc init()

A subclass of Applet should override this method if it has initialization to perform. For example, an applet with threads would use the init method to create the threads and the destroy method to kill them.

I guess you need to a long running initialization, therefore you should start a thread for that in the init() method.

stacker
+2  A: 

From the applet tutorial

init Method

The init method is useful for one-time initialization that doesn't take very long. The init method typically contains the code that you would normally put into a constructor. The reason applets don't usually have constructors is that they aren't guaranteed to have a full environment until their init method is called. Keep the init method short so that your applet can load quickly.

start Method

Every applet that performs tasks after initialization (except in direct response to user actions) must override the start method. The start method starts the execution of the applet. It is good practice to return quickly from the start method. If you need to perform computationally intensive operations it might be better to start a new thread for this purpose.

It looks like you have to create your own thread for long running methods.

josefx