I’m new to threads and am trying to replicate a simple example of interrupting a thread in my web app. I have the class below (ComputeResults has other variables and functions, setters/getters etc but this is the new code I can’t get to work):
@ManagedBean(name="results")
@RequestScoped
public class ComputeResults implements Serializable{
Thread scan;
public void testrun() {
scan = new Thread(new Runnable() {
@Override
public void run() {
int i = 0;
while (!Thread.currentThread().isInterrupted()) {
try {
i++;
if (i == 1) {
scan.interrupt();
}
}
catch (Exception e) {
Thread.currentThread().interrupt();
}
catch (Throwable t) {
System.out.println("Thrown test: "+t.getMessage());
}
}
}
});
scan.start();
}
public void stoprun() {
if(scan != null){
scan.interrupt();
}
}
}
In my interface I have a button to start the thread:
<p:commandLink action="submit" value="" onclick="testdialog.show()" oncomplete="testdialog.hide()" actionListener="#{results.testrun}" update="messages, runmsg, @form results" />
and one to attempt to interrupt it:
<p:commandButton action="submit" value="Cancel Test" onclick="testdialog.hide()" actionListener="#{results.stoprun}" update="messages, runmsg" />
Problem is the ‘stoprun’ function sees ‘scan’ as null and I’m not sure why. Adding scan.interrupt() inside testrun() works fine. I thought about using Thread.currentThread().interrupt() but it seems that the current thread ID/name is different when I call stoprun.
That’s because the bean is
@RequestScoped– each HTTP request (= button click) gets a new instance.You need to make it
@Scope("session")at least.