多次执行 ThreadPoolExecutor 后出现 OutOfMemoryError
OutOfMemoryError after executing a ThreadPoolExecutor many times
我使用使用 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”,我观察到“native”和“others" 每次调用此方法时内存都会增加。我尝试添加 future.cancel(true) 但没有成功。看起来池即使完成也保留在内存中。
Can anybody help and explain to me why?
Thanks in advance
每次调用 isOk
时,您都会创建一个 new ThreadPoolExecutor
,并且您 永远不会关闭它 .
您只向执行器提交一个作业,所以即使使用一个执行器,而不仅仅是创建一个新线程?
要么使用普通线程,要么重新使用在方法外部维护的执行器。
我使用使用 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”,我观察到“native”和“others" 每次调用此方法时内存都会增加。我尝试添加 future.cancel(true) 但没有成功。看起来池即使完成也保留在内存中。
Can anybody help and explain to me why? Thanks in advance
每次调用 isOk
时,您都会创建一个 new ThreadPoolExecutor
,并且您 永远不会关闭它 .
您只向执行器提交一个作业,所以即使使用一个执行器,而不仅仅是创建一个新线程?
要么使用普通线程,要么重新使用在方法外部维护的执行器。