JonasAnon JonasAnon - 15 days ago 5
Java Question

Threaded runnable object method not responding to changes

I have a class "HConnection" containing multiple methods such as abort(); and awaitConnection();

The awaitConnection(); method is called in my SWT Form main class using a runnable thread. Anyways, when i abort() the HConnection, the awaitConnection isn't aborted while it should be.

Have a look at this snapshot of my main code:

private HConnection connectie;

private void btnConnect_clicked(SelectionEvent e) {

if (btnNewButton_1.getText().equals("Connect")) {
String Url = combo.getText();
connectie = new HConnection(Url);
connectie.prepare();

new Thread(new Runnable() {
public void run() {
connectie.awaitConnection();

Display.getDefault().asyncExec(new Runnable() {
public void run() {
lblNewLabel_2.setText("Waiting -> client");
if (connectie.getState() == 2) {
lblNewLabel_2.setText("Replacing URL");
}
else {
lblNewLabel_2.setText("Failed");
connectie.abort();
btnNewButton_1.setText("Connect");
}
}
});
if (connectie.getState() == 2) {
// go on

}
}
}).start();

////////

btnNewButton_1.setText("Abort");
}
else if(btnNewButton_1.getText().equals("Abort")) {
connectie.abort();
lblNewLabel_2.setText("Aborted");
btnNewButton_1.setText("Connect");
}


And a snapshot of HConnection:

public void prepare() {
addToHostsFile("127.0.0.1" + "\t" + domain);
state = 1;
}

public void abort() {
removeFromHostsFile("127.0.0.1" + "\t" + domain);
waitingConnection = false;
HostFileEdited = false;
state = 0;
}

public void awaitConnection() {
if (state == 1) {
waitingConnection = true;
System.out.println("0");
while (/* not found && */ state == 1) {

// code

}
System.out.println("1");
waitingConnection = false;
if (state == 1) state = 2;
}

}


One more note; the abort() function did actually work and finished the thread when I tried calling connectie.abort() directly after the thread.start();, (placed "////////" in the code above on that spot)
But if it's called where it should be called, it do what it should do
while

lblNewLabel_2.setText("Aborted");
btnNewButton_1.setText("Connect");


are doing their job as expected

Answer

Make your state and awaitConnection volatile :

private volatile int state;
private volatile boolean awaitConnection;
Comments