So the title is explanatory, I want to wait on a thread for a max time say 1 sec, now within this 1 sec if the other thread receives a response then its fine, otherwise after 1 sec whether or not a response is recieved it should stop waiting and continue with its work, later I can wait for another 2 seconds to see if the response has arrived
Main Class:
atiReq.Now(); //asynchronous method returns immediatly
firstATIState = atiReq.getState(1000); // Wait for a max of 1000 ms to get the response
}
handleIDP();
if (isMobSub && firstATIState == null) {
//If ati response was not recived previously wait for another maximum 2000 ms now
firstATIState = atiReq.getState(2000);
}
AtiRequest Class:
/**
* Does an ATI Request asynchrounously
*/
public void Now() {
new Thread() {
public void run() {
atiReq.run();
synchronized (atiReq) {
try {
atiReq.wait(3000);
rawResponse = atiReq.ReturnXML;
logger.info("[" + refID + "] ATI Response recieved: " + rawResponse);
atiResponseRecieved = true;
atiReq.notify();
} catch (InterruptedException ex) {
logger.error("Error waiting on atiReq", ex);
}
}
}
}.start();
}
public String GetRawResponse() {
return rawResponse;
}
/**
* Gets the state of the ATI performed, waits for the ATI response for max
* period of timeout specified, returns null if response not arrived in
* specified time
*
* @param timeout the time to wait for response in milliseconds
* @return
*/
public ATIState getState(long timeout) {
synchronized (atiReq) {
while (!atiResponseRecieved) {
try {
atiReq.wait(timeout);
} catch (InterruptedException ex) {
logger.error("Error waiting on atiReq while trying to get aitState", ex);
}
}
}
if ("".equals(this.rawResponse)) {
//Response not recieved yet
logger.info("[" + refID + "] ATI Response not recived yet");
return null;
}
ATIState atiState = new ATIState(this.rawResponse);
return atiState;
}
Problem:
firstATIState = atiReq.getState(1000);
This line, in the main class, doesnt terminate after 1 sec, as you can see the corresponding code in getState(long timeout) method
while (!atiResponseRecieved) {
try {
atiReq.wait(timeout);
} catch (InterruptedException ex) {
logger.error("Error waiting on atiReq while trying to get aitState", ex);
}
}
is in a loop so I believe even if atiReq.wait(timeout) returns within 1 sec and if atiResponseRecieved is not true, it keeps on looping till the timeout of the Now() method exhausts and it sets atiResponseRecieved to true;
Question:
How do I solve this? I have tried removing it from the loop but then "spurious awakes" dont let it wait for complete 1 sec.
Is there any other work around for this?