我使用一个使用Future和Callable而不是AyscTask的线程池执行程序,利用超时功能的优势来等待响应,这可能需要花费一些时间才能调用我自己可以正常工作的方法,即“ isIdOk”。这是我进行池调用的方式:
public static boolean isOk(final Context context, final String id) {
boolean result = false;
final BlockingQueue<Runnable> workQueue = new LinkedBlockingQueue<>(1);
final ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(1, 1, 0, TimeUnit.SECONDS, workQueue);
Future<Boolean> future;
future = threadPoolExecutor.submit(new Callable<Boolean>() {
@Override
public Boolean call() {
return isIdOk(id);
}
});
try {result = future.get(5000,TimeUnit.MILLISECONDS);}
catch (ExecutionException e) {
e.printStackTrace();
}
catch (InterruptedException e) {
e.printStackTrace();
}
catch (TimeoutException e) {
e.printStackTrace();
}
future.cancel(true);
return result;
}
我称此方法(isOk)每分钟大约12次,并且效果很好,但是过一会儿,该方法使我失望:
java.lang.OutOfMemoryError: pthread_create (1040KB stack) failed: Try again
在此行:
future = threadPoolExecutor.submit(new Callable<Boolean>() {
Whatching arround Android Studio内存“ Profiler”,我观察到每次调用此方法时,“ stack”和“ others”的内存都会增加。我尝试添加future.cancel(true)失败。即使结束,看起来池仍保留在内存中。
有人可以帮我解释一下原因吗?在此先感谢
ThreadPoolExecutor
时创建一个new isOk
,而您从不关闭它。
要么使用普通线程,要么重新使用方法外部维护的执行程序。