为什么我的线程不会死并导致内存泄漏?

Chr*_*ris 5 multithreading android executor android-asynctask

我的应用程序正在积累很多ThreadGC无法接收和清除的实例.从长远来看,这种内存泄漏会使应用程序崩溃.

我不是100%肯定他们来自哪里,但我有一种明显的感觉,以下可能是有问题的代码:

public class UraHostHttpConnection extends AbstractUraHostConnection {
    private Handler uiThreadHandler = new Handler(Looper.getMainLooper());
    private Executor taskExecutor = new Executor() {
         public void execute(Runnable command) {
             new Thread(command).start();
        }
    };
    private ConnectionTask task = null;

    @Override
    public void sendRequest(final HttpUriRequest request) {
        this.task = new ConnectionTask();
        this.uiThreadHandler.post(new Runnable() {
            public void run() {
                task.executeOnExecutor(taskExecutor, request);
            }
        });
   }

    @Override
    public void cancel() {
        if (this.task != null)
            this.task.cancel(true);
    }
}
Run Code Online (Sandbox Code Playgroud)

这段代码允许我并行运行几个HTTP连接,这些连接在默认情况下不会相互阻塞AsyncTask Executor(这只是一个单线程队列).

我检查过,AsyncTask事实上它们正在达到他们的onPostExecute()方法而不仅仅是永远地运行.在检查了一些内存转储后,我怀疑包装Thread-Objects在AsyncTasks完成后没有停止运行.

上面的代码是否仍然可能导致我的内存泄漏,或者我应该开始寻找其他地方?

任何帮助表示赞赏.

编辑:应该注意,这sendRequest只是一次调用.上面示例中没有的代码的其他部分确保了这一点.

编辑2:超类看起来像这样:

public abstract class AbstractUraHostConnection {
    protected IUraHostConnectionListener listener = null;

    public void setListener(IUraHostConnectionListener listener) {
        this.listener = listener;
    }
    public abstract void sendRequest(HttpUriRequest request);
    public abstract void cancel();
}
Run Code Online (Sandbox Code Playgroud)

AsyncTask看起来像这样:

private class ConnectionTask extends AsyncTask<HttpUriRequest, Object, Void> {
    final byte[] buffer = new byte[2048];
    private ByteArrayBuffer receivedDataBuffer = new ByteArrayBuffer(524288);

    @Override
    protected Void doInBackground(HttpUriRequest... arg0) {
        UraHostHttpConnection.taskCounter++;
        AndroidHttpClient httpClient = AndroidHttpClient.newInstance("IVU.realtime.app");
        try {
            // Get response and notify listener
            HttpResponse response = httpClient.execute(arg0[0]);
            this.publishProgress(response);

            // Check status code OK before proceeding
            if (response.getStatusLine().getStatusCode() == 200) {
                HttpEntity entity = response.getEntity();
                InputStream inputStream = entity.getContent();
                int readCount = 0;

                // Read one kB of data and hand it over to the listener
                while ((readCount = inputStream.read(buffer)) != -1 && !this.isCancelled()) {
                    this.receivedDataBuffer.append(buffer, 0, readCount);
                    if (this.receivedDataBuffer.length() >= 524288 - 2048) {
                        this.publishProgress(receivedDataBuffer.toByteArray());
                        this.receivedDataBuffer.clear();
                    }
                }

                if (this.isCancelled()) {
                    if (arg0[0] != null && !arg0[0].isAborted()) {
                        arg0[0].abort();
                    }
                }
            }
        } catch (IOException e) {
            // forward any errors to listener
            e.printStackTrace();
            this.publishProgress(e);
        } finally {
            if (httpClient != null)
                httpClient.close();
        }

        return null;
    }

    @Override
    protected void onProgressUpdate(Object... payload) {
        // forward response
        if (payload[0] instanceof HttpResponse)
            listener.onReceiveResponse((HttpResponse) payload[0]);
        // forward error
        else if (payload[0] instanceof Exception)
            listener.onFailWithException((Exception) payload[0]);
        // forward data
        else if (payload[0] instanceof byte[])
            listener.onReceiveData((byte[]) payload[0]);
    }

    @Override
    protected void onPostExecute(Void result) {
        listener.onReceiveData(this.receivedDataBuffer.toByteArray());
        listener.onFinishLoading();
        UraHostHttpConnection.taskCounter--;
        Log.d(TAG, "There are " + UraHostHttpConnection.taskCounter + " running ConnectionTasks.");
    }
}
Run Code Online (Sandbox Code Playgroud)

Mar*_*mic 1

用 ThreadPoolExecutor 替换您的 Executor,以便您可以控制池的大小。如果 ThreadPoolExecutor 基本上是一个具有公开方法的 Executor,则可能只是默认最大池大小设置得非常高的情况。

官方文档在这里

特别看一下:

setCorePoolSize(int corePoolSize)
//Sets the core number of threads.

setKeepAliveTime(long time, TimeUnit unit)
//Sets the time limit for which threads may remain idle before being terminated.

setMaximumPoolSize(int maximumPoolSize)
//Sets the maximum allowed number of threads.
Run Code Online (Sandbox Code Playgroud)

如果您想减少编码,还有一个替代方案(更好的想法取决于您真正想要多少控制权以及您将交易多少代码来获得它)。

Executor taskExecutor = Executors.newFixedThreadPool(x);
Run Code Online (Sandbox Code Playgroud)

其中 x = 池的大小