【问题标题】:OutOfMemoryError after executing a ThreadPoolExecutor many times多次执行 ThreadPoolExecutor 后出现 OutOfMemoryError
【发布时间】:2019-10-28 03:00:47
【问题描述】:

我使用使用 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>() {

围绕 Android Studio 内存“Profiler”,我观察到“native”和“others”内存在每次使用此方法时都会增加叫做。我尝试添加 future.cancel(true) 没有成功。看起来池即使完成也保留在内存中。

谁能帮我解释一下为什么? 提前致谢

【问题讨论】:

    标签: java android future threadpoolexecutor callable


    【解决方案1】:

    每次调用isOk 时,您都会创建一个 ThreadPoolExecutor,并且您永远不会将其关闭

    您只向执行器提交一个作业,所以即使使用执行器,而不仅仅是创建一个新线程?

    要么使用普通线程,要么重用在方法外部维护的执行器。

    【讨论】:

    • Oh myyy!,谢谢@Andreas,我想念 threadPoolExecutor.shutdown 或 purge 方法。顺便说一句,我会听取你的建议来重用它。再次感谢
    猜你喜欢
    • 2015-08-09
    • 1970-01-01
    • 2014-01-04
    • 1970-01-01
    • 2023-01-27
    • 1970-01-01
    • 1970-01-01
    • 2012-11-23
    • 2017-04-11
    相关资源
    最近更新 更多