java - OutOfMemoryError after executing a ThreadPoolExecutor many times
问题描述
I use a thread pool executor using Future and Callable instead of AyscTask, taking the advantage of the timeout feature to wait for a response that can take a while calling my own method that works ok called "isIdOk". This is the way I do the pool call:
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;
}
I call this method (isOk) about 12 times per minute and works perfect, but after a while, the method throws me:
java.lang.OutOfMemoryError: pthread_create (1040KB stack) failed: Try again
in this line:
future = threadPoolExecutor.submit(new Callable<Boolean>() {
Whatching arround Android Studio memory "Profiler", I observe that the "native" and "others" memory increase each time this method is called. I have try adding future.cancel(true) without success. It looks like the pool remains in memory even if it finishes.
Can anybody help and explain to me why? Thanks in advance
解决方案
You create a new ThreadPoolExecutor
every time isOk
is called, and you never shut it down.
You only ever submit one job to the executor, so even use an executor, and not just create a new thread?
Either use plain threads, or re-use an executor maintained outside the method.
推荐阅读
- sharepoint - 如何以编程方式使用 pnp csom 删除 SharePoint 网站集
- jquery - jQuery版本检查
- doctrine-orm - 如何在其他查询中使用 QueryBuilder 格式化查询重用格式化的 Doctrine 2
- java - 如何通过像我在这里所做的那样传递以下程序中的数组大小为 6?
- ruby - 在 Ruby 中,惯用且干净地改进了 split 和 map 的使用,将字符串输入转换为 2d int 数组(即矩阵)
- python - Flask + gunicorn + meinheld 提供静态内容
- ios - 单独的 BundleName 和应用程序图标下显示的名称
- java - 从 IntelliJ 中的数据库自动创建 POJO 类
- php - substr() 中的 PHP 变量作为长度未执行
- r - Shiny:通过单击 valueBox 触发弹出窗口