我在应用程序中遇到如下OutOfMemory错误:
OutOfMemoryError: Unable to Create New Native Thread
我看到许多线程如下:
OkHttp ConnectionPool - priority:5 - threadId:0x00007ff5a0060800 - nativeId:0xc5df - nativeId (decimal):50655 - state:TIMED_WAITING
stackTrace:
java.lang.Thread.State: TIMED_WAITING (on object monitor)
at java.lang.Object.wait(Native Method)
at java.lang.Object.wait(Object.java:460)
at okhttp3.ConnectionPool$1.run(ConnectionPool.java:67)
- locked <0x00000006c12436a0> (a okhttp3.ConnectionPool)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
at java.lang.Thread.run(Thread.java:748)
似乎我没有按照我的意愿关闭连接响应,下面是我拥有的代码:
Response<T> response = call.execute(); // Call<T> call
if( response.isSuccessful() )
{
return response.body();
}
else
{
...
}
如何关闭响应?如果我知道它将返回的内容,这就是我要做的事情:
Response<ResponseBody> response = call.execute(); // Call<ResponseBody> call
if( response.isSuccessful() )
{
try (ResponseBody body = response.body())
{
if( body != null )
{
return new String( body.bytes() );
}
}
return null;
}
else
{
....
}
我看到我也没有为OkHttpClient定义连接池。这可能是问题吗?如果未定义会发生什么,会继续创建新的连接并因此导致此泄漏吗?