多線程下載圖片時,偶發卡死在 in.read(buf),線程無法結束,資源洩漏。
URL url = new URL(imgUrl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(5000); // 5s 連接超時
conn.setReadTimeout(15000); // 15s 讀取超時
InputStream in = conn.getInputStream();
try-with-resources 確保流關閉:
try (BufferedInputStream in = new BufferedInputStream(conn.getInputStream());
BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(file))) {
byte[] buf = new byte[8192];
int len;
while ((len = in.read(buf)) != -1) out.write(buf, 0, len);
}
read 返回值、耗時、異常堆疊,定位具體卡死環節生產環境推薦使用 OkHttp 或 Apache HttpClient,內建連接池、超時重試、取消機制,避免手動管理底層流。