假设我在客户端Java应用程序(即Android应用程序)中有一个方法
ExecutorService pool = ExecutorsService.newFixedThreadPool(1); //1 thread in pool
public void makeHTTPRequestVeryVeryCostly() {
/* IN A BACKGROUND THREAD */
CompleteableFuture<String> s = CompleteableFuture.supplyAsync(() -> makeCostlyReq, pool));
s.get();
updateTheUserUIInTheMainUIThread(s); //Update with s
}
button.onClicklistener((b) -> makeHTTPRequestVeryVeryCostly()); // some button in the UI that will make the http request
在愤怒中,用户点击按钮100次,然后100个请求被提交到ThreadPool中。2件糟糕的事情发生了:
(1)代价高昂的请求计算100次
(2)每次返回后,UI刷新100次。
这些都是非常大的问题。在Java中,解决这个问题的方法是什么?最好是在一个成功的请求之后终止线程池中的所有先前请求,该如何做到这一点呢?
发布于 2019-07-15 09:21:43
如果您想发送每个http请求,但不想并发。Lock
可能会在这方面对你有所帮助。下面是伪代码:
ExecutorService pool = ExecutorsService.newFixedThreadPool(1); //1 thread in pool
Lock httpRequestLock = new ReentrantLock();
public void makeHTTPRequestVeryVeryCostly() {
boolean locked = httpRequestLock.tryLock(10, TimeUnit.SECONDS);
if(!locked){
//can't get the request lock util timeout(10s)
return;
}
try{
/* IN A BACKGROUND THREAD */
CompleteableFuture<String> s = CompleteableFuture.supplyAsync(() -> makeCostlyReq, pool));
s.get();
updateTheUserUIInTheMainUIThread(s); //Update with s
}finally{
httpRequestLock.unlock();
}
}
button.onClicklistener((b) -> makeHTTPRequestVeryVeryCostly()); // some button in the UI that will make the http request
我们使用一个Lock
来保证同一时间只有一个请求,并在get lock发送请求时为后续请求设置超时。
另外还有,如果你只是想让用户以较低的频率发送请求,比如1次/10s。您可以声明一个变量来保存上次发送请求的时间,并且每次检查上次执行时间和当前时间之间的持续时间。
https://stackoverflow.com/questions/57032239
复制相似问题