I'm making a client-server application, in which the user can turn on or switch off the server from a gui; in order to let it work, I use a SwingWorker nested class. All seems to work correctly, but when I switch off the server and re-turn it on it doesn't work, probably because there is still another instance open of it that can't be overwritten: server is blocked on the accept() method. I want to kill the previous instance when the user presses the switch off button, but I don't know how.
Here's the SwingWorker class that gives me problems:
class SwingWorkGUI extends SwingWorker
{
@Override
protected Integer doInBackground() throws Exception {
int delay = 1000;
final Timer time = new Timer(delay, null);
time.addActionListener( new java.awt.event.ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (Server.up == true){
upTimeMillis += 1000;
long diff = upTimeMillis/1000;
long numHrs = diff/60;
diff = diff%60;
long numMins = diff/60;
long numSecs = diff%60;
upTime.setText(numHrs + ":" + numMins + ":" + numSecs);
}
else {
upTime.setText("Server Actually Down");
time.stop();
}
}
});
time.start();
mainServer = new Server();
return null;
}
}
Everytime the Turn On button is pressed, the actionPerformed determines whether the server is already on or not, then if not runs
SwingWorkGUI swg = new SwingWorkGUI();
swg.execute();
The execution blocks in the following instruction, but only the second (third,ecc.) time it is called:
mainServer = new Server();
Server.up is a static variable that helps me to kill the while(true) method in server.
How can I kill the open instance without closing all the application?