Why won't my threads die and cause a memory leak?

My application has accumulated many instances Threadthat the GC cannot pick up and remove. This memory leak causes the application to crash in the end.

I am not 100% sure where they come from, but I feel that the following code may be as follows:

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);
    }
}

This code allows me to start several HTTP connections in parallel, which will not block each other by default AsyncTask Executor(which is only one queue with a stream).

I checked that they AsyncTaskactually achieve their methods onPostExecute()and do not just start forever. After checking some memory dumps, I suspect that Thread-Objects wrap does not stop after completion AsyncTask.

, - ?

.

: , 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();
}

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.");
    }
}
+5
1

ThreadPoolExecutor , . ThreadPoolExecutor Executor , , .

doc .

, , :

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.

, ( , , ).

Executor taskExecutor = Executors.newFixedThreadPool(x);

x =

+1

All Articles