terminating java applet thread on page unload
Posted
by Hammad Tariq
on Stack Overflow
See other posts from Stack Overflow
or by Hammad Tariq
Published on 2010-01-25T17:07:40Z
Indexed on
2010/04/09
7:23 UTC
Read the original article
Hit count: 676
Hello, I have got a problem here in terminating the threads. The problem is that I am using applet thread to access JS DOM and manipulate innerHTML of a span to right the Thread Name as the innerHTML. It works fine until I keep refreshing the page but if I dont give it a sleep of like 200ms and go to another page which dont have any applet on it, it will give me an error in firebug console:
document.getElementById("userName") is null
What I am suspecting is, although I send an interrupt on stop and I have also tried the same by setting a flag variable of running in run while loop, the thread executes much faster than the time JVM takes to unload it and I get my page changed in browser but applet is still trying to find an element with id userName.
Is that true? Is there any work around of it? Is there any way to know how many threads are running at the moment? Is there any kill all command to send on destroy()?
I have searched a lot, seen all the API of java threads and applets, couldn't get this to work.
Below is the code:
import java.applet.Applet;
import netscape.javascript.*;
//No need to extend JApplet, since we don't add any components; //we just paint. public class firstApplet extends Applet {
/**
*
*/
private static final long serialVersionUID = 1L;
firstThread first;
boolean running = false;
public class firstThread extends Thread{
JSObject win;
JSObject doc;
firstThread second;
public firstThread(JSObject window){
this.win = window;
}
public void run() {
try{
System.out.println("running... ");
while (!isInterrupted()){
doc = (JSObject) win.getMember("document");
String userName = Thread.currentThread().getName();
//String userName = "John Doe";
String S = "document.getElementById(\"userName\").innerHTML = \""+userName+"\";";
doc.eval(S);
Thread.sleep(5);
}
}catch(Exception e){
System.out.println("exception in first thread... ");
e.printStackTrace();
}
}
}
public void init() {
System.out.println("initializing... ");
}
public void start() {
System.out.println("starting... ");
JSObject window = JSObject.getWindow(this);
first = new firstThread(window);
first.start();
running = true;
}
public void stop() {
first.interrupt();
first = null;
System.out.println("stopping... ");
}
public void destroy() {
if(first != null){
first = null;
}
System.out.println("preparing for unloading...");
}
}
Thanks
© Stack Overflow or respective owner