我的应用程序正在积累许多GC无法接收和清除的Thread
个实例。从长远来看,这种内存泄漏会使应用程序崩溃。
我不是 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);
}
}
此代码允许我并行运行多个HTTP连接,这些连接不会在默认的AsyncTask
Executor
(这只是一个单线程队列)上相互阻塞。
我检查过,AsyncTask
实际上正在达到他们的onPostExecute()
方法并且不会永远运行。在检查了一些内存转储后,我怀疑包裹Thread
- 在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.");
}
}
答案 0 :(得分:1)
为您的Executor替换ThreadPoolExecutor,以便您可以控制池的大小。如果ThreadPoolExecutor基本上是具有公开方法的Executor,则可能只是将默认最大池大小设置得非常高。
官方文件here。
特别注意:
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 =游泳池的大小