public void sendRequestSynch(final NetworkRequest request, long timeout) throws Exception {sendRequestAsynch是異步的API。這個是寫作過程中的一個版本。在revIEw之後發現其中存在同步問題。synchronized (request)不是在啟動孫子線程tt之後執行。問題在於如果sendRequest(request)在執行到最後是發送request.notifyAll()時,可能還沒有執行synchronized (request) 。這樣就存在request.wait(timeout)不會被喚醒而超時的問題。
synchronized (request) {
Thread t = new Thread() {
public void run() {
try {
log.debug("send request in another thread.");
sendRequest(request);
}catch (Exception e) {
log.warn(e.getMessage());
}
log.debug("Exit the thread.");
}
};
t.start();
log.debug("Try to wait for " + timeout);
request.wait(timeout);
if (request.isDelayed()) {
queue.removeElement(request);
timeoutQueue.addElement(request);
log.debug("Request TIMEOUT !!!!!!!!!!!!!!!!");
log.debug("Stop the network request thread for the timeout.");
}else {
log.debug("Be NotifIEd and wakeup.");
}
}
}
public void sendRequestAsynch(final NetworkRequest request, final long timeout) throws Exception {應當把sendRequest(request) 放到同步塊中。改正後的代碼:
Thread t = new Thread() {
public void run() {
try {
log.debug("send request in another thread.");
Thread tt = new Thread() {
public void run() {
try {
log.debug("send request in grandson thread. " + request.getSequenceId());
sendRequest(request);
}catch (Exception e) {
log.warn(e.getMessage());
}
}
};
tt.start();
synchronized (request) {
log.debug("Try to wait for " + timeout + " " + request.getSequenceId());
request.wait(timeout);
if (request.isDelayed()) {
queue.removeElement(request);
timeoutQueue.addElement(request);
log.debug("Request TIMEOUT !!!!!!!!!!!!!!!!");
log.debug("Stop the network request thread for the timeout.");
}else {
log.debug("Be NotifIEd and wakeup.");
}
}
}catch (Exception e) {
log.warn(e.getMessage());
}
log.debug("Exit the thread.");
}
};
t.start();
}
public void sendRequestAsynch(final NetworkRequest request, final long timeout) throws Exception {exception的處理還沒有規范起來。許多細節還待完善(post還沒有被支持),...
Thread t = new Thread() {
public void run() {
try {
log.debug("send request in another thread.");
synchronized (request) {
Thread tt = new Thread() {
public void run() {
try {
log.debug("send request in grandson thread. " + request.getSequenceId());
sendRequest(request);
}catch (Exception e) {
log.warn(e.getMessage());
}
}
};
tt.start();
log.debug("Try to wait for " + timeout + " " + request.getSequenceId());
request.wait(timeout);
if (request.isDelayed()) {
queue.removeElement(request);
timeoutQueue.addElement(request);
log.debug("Request TIMEOUT !!!!!!!!!!!!!!!!");
log.debug("Stop the network request thread for the timeout.");
}else {
log.debug("Be NotifIEd and wakeup.");
}
}
}catch (Exception e) {
log.warn(e.getMessage());
}
log.debug("Exit the thread.");
}
};
t.start();
}