I am using a "transceiver" to send a request from the client to the server and wait for the response. I learned from [here][1] the way to communicate between two threads and wrote bellow codes:
public class ThreadEvent {
private Object lock;
private Object data;
private String ntfInfo;
public ThreadEvent() {
data = null;
lock = new Object();
ntfInfo = "NONE";
}
public boolean await(int time) {
synchronized (lock) {
try {
lock.wait(time);
return true;
} catch (InterruptedException ex) {
LogManager.ex(ex);
return false;
}
}
}
public void signal() {
synchronized (lock) {
ntfInfo = (new Throwable()).getStackTrace()[1].getMethodName() + "@"
+ (new Throwable()).getStackTrace()[1].getClassName() + "@"
+ "line" + (new Throwable()).getStackTrace()[1].getLineNumber() + "@"
+ (new Throwable()).getStackTrace()[1].getFileName();
lock.notify();
}
}
public synchronized void putData(Object data) {
this.data = data;
}
public synchronized Object takeData() {
Object res = data;
data = null;
return res;
}
public String takeNtfInfo() {
String info = ntfInfo;
ntfInfo = "NONE";
return info;
}
}
I found sometimes the send-and-wait thread was not always been notified by the response, nor been interrupted, (as per my understanding) but was awaked from the wait by some mysterious "thing". Here is the log:
1460717223039:DEBUG:1 starting... @<init>@wsclientapp.GUIManager@line57@GUIManager.java
1460717229475:DEBUG:2 transceive()@line30@WSTransceiver.java
1460717229735:DEBUG:3 forward()@line69@WSTransceiver.java
1460717229739:DEBUG:4 transceive(ivoked by: forward@wsclientapp.util.WSTransceiver@line73@WSTransceiver.java)@line42@WSTransceiver.java
1460717229750:DEBUG:5 transceive()@line30@WSTransceiver.java
1460717229768:DEBUG:6 forward()@line69@WSTransceiver.java
1460717229768:DEBUG:7 transceive(ivoked by: forward@wsclientapp.util.WSTransceiver@line73@WSTransceiver.java)@line42@WSTransceiver.java
1460717229770:DEBUG:8 transceive()@line30@WSTransceiver.java
1460717234771:DEBUG:9 transceive(ivoked by: NONE)@line42@WSTransceiver.java
You may see line2/3/4 is a transaction, and line5/6/7 is another transaction, but line8/9 shows the problem. If the transceive was awaked by someone, it should print the name of the thread, or if it's been interrupted, it should print the exception stack by the LogManager.ex(ex). But it didn't. What I did wrong?