基本上这段代码执行http请求,如果http请求超时,它会重置wifi连接(有时必须这样做,就是这样,我也可以是其他非android相关的东西,而不是“reset wifi联系”)。
必须考虑以下特殊情况:
- 如果当前有 1 个或多个线程正在执行 http 请求,则不允许其他线程重置 wifi 连接
- 如果 1 个线程当前已经在重置 wifi 连接,而另一个线程即将重置 wifi 连接,则直接发送后一个线程重试 http 请求(当前一个线程完成 wifi 重置时)
- 当前正在重置 wifi 连接时不执行 http 请求
- => 一次只有 1 个线程可以修复 wifi 连接,但多个线程可以同时发起 http 请求
这让我很头疼。
到目前为止,这是我的代码。我可以改进什么?
static int requestsActive = 0;
protected int requestTry = 0;
static final int maxTrys = 2;
static final ReentrantLock wifiLock = new ReentrantLock();
public void evaluate() throws Exception {
try {
requestTry++;
while (wifiLock.isLocked()) // no not start new http request while wifi is being fixed
Thread.sleep(400);
requestsActive++; //increment so that another thread that wants to fix wifi knows it has to wait
response = httpClient.execute(requestBase);
requestsActive--; // when == 0 wifi can be fixed if it needs to
} catch (ConnectTimeoutException e) {
requestsActive--; //same as above (for exception case)
if (requestTry == maxTrys)
throw new ConnectTimeoutException("maxTrys reached");
if (!wifiLock.tryLock()) //another thread is currently fixing wifi, no need to do it myself
evaluate(); // ...so start a new http request
while (requestsActive > 0) // wait until no more threads are in the http request section above
Thread.sleep(400);
WifiManager wifiMan = (WifiManager) App.getContext().getSystemService(Context.WIFI_SERVICE);
resetWifi(wifiMan); //reset android wifi, nothing special
wifiLock.unlock();
evaluate();
}