0

基本上这段代码执行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();
}
4

1 回答 1

1

不幸的是,我不能保证这会奏效,因为我没有安装 Android 模拟器并且很快就把它放在一起。希望它至少作为一个可以构建的概念对您有所帮助。基本上,它使用信号量来允许一次尝试有限数量的请求,并且当连接超时时,它将获取信号量的所有许可,这将阻止在 wifi 重置时发出任何新请求。这利用了 Java 代码库中已经存在的并发代码,因此您不必自己重新实现任何代码。

您可以在此处查看信号量的 JavaDoc 。

static final int MAX_CONCURRENT_REQUESTS = 10;
static final Semaphore httpRequestsLock = new Semaphore(MAX_CONCURRENT_REQUESTS, true);

public void evaluate() throws Exception {
    Foo requestBase = null;
    HttpClient httpClient = new HttpClient();

    httpRequestsLock.acquire();
    try{
        response = httpClient.execute(requestBase);
    }
    catch (ConnectTimeoutException e) {
        httpRequestsLock.release();
        httpRequestsLock.acquire(MAX_CONCURRENT_REQUESTS); // Blocks until all current requests are done
        WifiManager wifiMan = (WifiManager) App.getContext().getSystemService(Context.WIFI_SERVICE);
        resetWifi(wifiMan); //reset android wifi, nothing special
        httpRequestsLock.release(MAX_CONCURRENT_REQUESTS);
        evaluate();
    }
}
于 2013-01-06T21:25:29.323 回答