首页 > 解决方案 > 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

标签: javaandroidfuturethreadpoolexecutorcallable

解决方案


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.


推荐阅读