java大量独读写小文件内存增加。

aeaxea42 2016-07-06 11:43:05
建立100个线程,每个线程下载100个文件。要求长连接下载。我用多线程掉如下这段核心代码,却发现下载时内存不断增加,请问如下代码怎么优化?

====
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;

public class Main {

private static Socket socket;
private static InputStream is;
private static PrintWriter writer;

public static void main(String[] args) throws IOException{
socket=new Socket("tmp.518ccc.com",80);
is=socket.getInputStream();
writer=new PrintWriter(socket.getOutputStream());
get("/vmp/vnc.exe","vnc.exe");
get("/vmp/lcx.exe","lcx.exe");
get("/vmp/tm.mini.tar","tm.mini.tar");
writer.close();
is.close();
socket.close();
}

private static String nextLine() throws IOException{
StringBuilder sb=new StringBuilder();
while(true){
int b=is.read();
if(b==10){
break;
}
if(b!=13){
sb.append((char)b);
}
}
return sb.toString();
}

private static void get(String path, String filename) throws IOException {
System.out.println(path);
writer.println("GET "+path+" HTTP/1.1");
writer.println("Host: tmp.518ccc.com");
writer.println("Connection: keep-alive");
writer.println();
writer.flush();
int length=0;
String line=nextLine();
while(!"".equals(line)){
System.out.println(line);
if(line.startsWith("Content-Length:")){
length=Integer.parseInt(line.substring(16));
}
line=nextLine();
}
byte[] buf=new byte[1024];
int len;
System.out.println(length);
OutputStream fos=new FileOutputStream(filename);
try{
while(length>0&&(len=is.read(buf, 0, Math.min(length, 1024)))>0){
fos.write(buf, 0, len);
length-=len;
System.out.println(length);
}
}finally{
fos.close();
}
}
}
...全文
168 1 打赏 收藏 转发到动态 举报
写回复
用AI写文章
1 条回复
切换为时间正序
请发表友善的回复…
发表回复
qq_15915835 2016-07-07
  • 打赏
  • 举报
回复
dump一下jvm内存。用工具分析下内存都用到哪里了。用MAT等。

50,530

社区成员

发帖
与我相关
我的任务
社区描述
Java相关技术讨论
javaspring bootspring cloud 技术论坛(原bbs)
社区管理员
  • Java相关社区
  • 小虚竹
  • 谙忆
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧