我正在調用REST URL並嘗試測量獲取響應所花費的時間。BasicClientConnManager的無效使用:仍然分配的連接
我正在使用DefaultHttpClient
來獲得REST URL
的響應。
在我的下面的程序中,每個線程將在一個特定的範圍內工作。像每個線程將工作之間1 - 100
和第二個線程將工作之間101 - 200
等
SO在我的下面的代碼,它第一次工作正常。但第二次,是在這條線httpclient.execute
拋出異常的第二次原樣
java.lang.IllegalStateException: Invalid use of BasicClientConnManager: connection still allocated.
Make sure to release the connection before allocating another one.
有什麼不對,我在這裏做什麼? -
下面是我的代碼 -
class Task implements Runnable {
private DefaultHttpClient httpclient = new DefaultHttpClient();
private HttpGet httpGet;
private HttpResponse response;
@Override
public void run() {
try {
httpGet = new HttpGet(
"http://localhost:8080/service/BEService/v1/get/USERID=10000/profile.ACCOUNT.SERVICE
httpGet.getRequestLine();
for (int userId = id; userId < id + noOfTasks; userId++) {
long start = System.nanoTime();
response = httpclient.execute(httpGet);
long end = System.nanoTime() - start;
}
} catch (Exception e) {
LOG.error("Threw a Exception in " + getClass().getSimpleName(), e);
}
}
}
更新的代碼: -
如果我做它像這個 -
東西class Task implements Runnable {
private DefaultHttpClient httpclient = new DefaultHttpClient();
private HttpGet httpGet;
private HttpResponse response;
@Override
public void run() {
try {
for (int userId = id; userId < id + noOfTasks; userId++) {
httpGet = new HttpGet("http://localhost:8080/service/BEService/v1/get/USERID=10000/profile.ACCOUNT.SERVICE");
httpGet.getRequestLine();
long start = System.nanoTime();
response = httpclient.execute(httpGet);
long end = System.nanoTime() - start;
HttpEntity entity = response.getEntity();
EntityUtils.consume(entity);
}
} catch (Exception e) {
LOG.error("Threw a Exception in " + getClass().getSimpleName(), e);
}
}
}
那麼它是好還是不好?
感謝瑞安的建議。我已經更新了代碼。如果我這樣做,那麼我會遇到任何問題? – AKIWEB 2013-02-14 01:39:04
從你展示的片段中很難說。這聽起來像你有一個HttpClient跨越線程,這是基本的連接管理器不允許的。我想這也可能是因爲你沒有在第一個版本中正確[釋放低級資源](http://hc.apache.org/httpcomponents-client-ga/tutorial/html/fundamentals.html#d5e139)案件。 – 2013-02-14 01:44:51
糾正我,如果我錯了,但在他的代碼httpClient不共享。在C#中,線程是一種方法,但在Java中它是整個類(jj09.net/multithreading-csharp-vs-java)。所以是的問題是資源發佈(https://www.securecoding.cert.org/confluence/x/9gFqAQ,https://hc.apache.org/httpcomponents-core-ga/httpcore/apidocs/org/apache /http/util/EntityUtils.html#consume(org.apache.http.HttpEntity))。 – 2016-02-17 12:49:00