Thanks for sharing! But please update the code to better support the
Applet Lifecycle and implement all
methods for best robustness.
For example the start-Method() might be called multiple times, so you should not simple spawn a new threads there (you might get multiple instances running in parallel). Better check, if the thread was already spawned and only wake it up. Also you should include means to suspend the rendering on stop() and do clean up in destroy().
Alternatively (e.g. to circumvent browsers that don't pass correct notifications to the applet) you could simple kill and clean up in stop() and destroy() and restart the applet in start(). But you also need to check if the Thread is already there and kill it before spawning a new one.
Hello, thank you for the feedback. I had already read the applet the applet section in the past and some of my design decision were based on it. But it's always good to refresh your memory. In the "methods" page, it said the following about 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."
That's why I'm starting a new thread in the start method. Although, I agree with you that I need some means to kill a thread. I did some testing and I found out that effectively my thread continue to run after the stop method of the applet is called. But, the thread is then killed by the code :
1 2 3
| if(!isActive()){ return; } |
I could possibly replace this code by overriding the stop method with the following code, which would nearly do the same.
1 2 3 4
| @Override public void stop(){ running = false; } |
But the following code could produce some synchronization problem if the 2 threads access the running variable at the same time. So a safer version would look like it.
1 2 3 4 5 6 7 8 9 10
| @Override public void stop(){ setRunning(false); } private synchronized void setRunning(boolean running){ this.running = running; } private synchronized boolean isRunning(){ return running; } |
In all case, the thread will stop to run (and in the process destroy itself because it is no longer in use). So starting a new one shouldn't be a problem. But which version is better? Or any other suggestion.
Another thing, that I could/should? change is putting the initialization code in the init() method instead of the start method. I don't think it does any difference but it might be good practice.
Btw, there is one thing that I don't understand. How can an applet call the start method more than once? I was sure that the methods were always called in order (init(), start(), stop() and destroy())