凌空队列抛出OutOfMemoryError“ pthread_create

时间:2018-06-25 07:20:49

标签: android android-volley

每次我发出请求时,我都会创建一个新的Volley请求队列:

public void initializeQueue(Context context){

    File cacheDir = new File(context.getCacheDir(), "Volley");
    this.queue = new RequestQueue(new DiskBasedCache(cacheDir), new BasicNetwork(new HurlStack()), MAX_SIZE_THREAD_POOL);
    this.queue.start();
}

当我完成请求时,我会清理变量

this.queue = null;

但是,当我提出很多请求时,将引发错误“ Throwing OutOfMemoryError“ pthread_create”。因此,我搜索了Internet,得出的结论是只启动一次队列。

但是我的问题是,如果我不断创建新的队列,为什么内存会不断增加?我将变量设置为可为空,以便旧队列无法访问且GC可收集。还有其他东西在排队吗?

注意 对于上面的上下文,使用应用程序。

谢谢

1 个答案:

答案 0 :(得分:1)

我对这个问题的有根据的猜测是:

上下文:
您正在将应用程序上下文传递到队列。因此它将保留引用,直到应用程序运行为止。

代码

this.queue = null;

由于此代码将只清除其保存的引用,而不清除其占用的内存。从内存中清除它的GC的工作,您无法保证GC何时会调用。

为什么要为每个请求创建一个新的RequestQueue。您可以检查null。创建队列并使用相同的队列进行进一步处理。

File cacheDir = new File(context.getCacheDir(), "Volley");
if( this.queue == null ){
   this.queue = new RequestQueue(new DiskBasedCache(cacheDir), new BasicNetwork(new HurlStack()), MAX_SIZE_THREAD_POOL);
}

资源:- Understanding contextUnderstanding reference

相关问题