I'm trying to get familiar with RMI, after creating my server and client. I'm looking now to create a method that will allow an AdministratorClient to stop a thread (in case it takes too long to process).
I tried using
interrupt()
but when I get the stackTrace of all thread I still see the one that was supposed to be stopped.
Here's the code for the AdminMethod
(in the server), where I'm trying to implement the killThread
method :
import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;
import java.util.Set;
public class AdminMethod extends UnicastRemoteObject implements AdminInterface{
protected AdminMethod() throws RemoteException {}
public String getThreadList() throws RemoteException {
Set<Thread> setOfThread =Thread.getAllStackTraces().keySet();
return setOfThread.toString();
}
public void killThread(long ThreadId) throws RemoteException {
Set<Thread> setOfThread = Thread.getAllStackTraces().keySet();
for(Thread thread : setOfThread){
if(thread.getId()==ThreadId){
thread.interrupt();
}
}
}
}
And here's the AdministratorClient
:
import java.rmi.Naming;
import java.util.Scanner;
public class AdministrationClient {
public static void main (String[] args) {
AdminInterface AdminProxy;
try {
AdminProxy = (AdminInterface)Naming.lookup("rmi://localhost/CBA");
String ThreadList = AdminProxy.getThreadList();
System.out.println(""+ThreadList);
Scanner sc = new Scanner(System.in);
System.out.println("Veuillez saisir un ID :");
long Id = sc.nextLong();
AdminProxy.killThread(Id);
System.out.println("Le thread "+Id+" a été correctement supprimé");
ThreadList = AdminProxy.getThreadList();
System.out.println(""+ThreadList);
sc.close();
}catch (Exception e) {
System.out.println("AdminClient exception: " + e);
}
}
}
I've seen numerous answers about a way to stop a thread, with using a flag. But I don't know how to implement it since the thread is created automatically, it's not a custom thread of which I can override the run()
method.
Can you please tell me what can I do about this ? Even a hint would do ! Thanks