我设置了一个服务器,当用户打开我的应用程序时,它会检查来自文件服务器的更新,并在必要时下载它们。
但是,我注意到,随着时间的推移,随着人们的连接和下载,服务器的内存使用量逐渐增加,只有当我重新启动打开套接字以托管文件的Java程序时,服务器的内存使用量才会下降。
程序的主要部分包含在下面:
@Override
public void run() {
try {
int archiveCount = in.readByte();
while(archiveCount-- > 0) {
int nameLength = in.readInt();
byte[] name = new byte[nameLength];
in.read(name);
int size = in.readInt();
clientLengths.put(new String(name).toLowerCase().trim(), size);
}
if(!clientLengths.isEmpty()) {
int count = 0;
for(String fileName : lengths.keySet()) {
if(!clientLengths.containsKey(fileName) ||
(long)clientLengths.get(fileName) != (long)lengths.get(fileName)) {
missing.add(fileName);
count += lengths.get(fileName);
}
}
if(count == 0) {
out.writeByte(0);
} else {
out.writeByte(1);
byte[] archive = readFile(archiveZip);
out.writeInt(count);
readFully(new ByteArrayInputStream(archive), out, archive.length);
}
} else { //hit if cache doesnt exist
out.writeByte(2);
byte[] cache = readFile(cacheZip);
out.writeInt(cache.length);
readFully(new ByteArrayInputStream(cache), out, cache.length);
}
destroy();
} catch(Exception e) {
e.printStackTrace();
}
}
private void destroy() throws IOException {
System.out.println("Finished cache handling from: " + socket.getInetAddress());
missing.clear();
clientLengths.clear();
socket.close();
}
变量定义如下:
private final Socket socket;
private final DataInputStream in;
private final DataOutputStream out;
private final List<String> missing = new ArrayList<>();
private final HashMap<String, Integer> clientLengths = new HashMap<>();
private final static HashMap<String, Integer> lengths = new HashMap<>();
private final static File dir = new File("./Data/Archive");
private final static File archiveZip = new File("./Data/Archive.zip");
private final static File cacheZip = new File("./Data/Cache.zip");
首先打开套接字的单独类中的主循环如下所示:
@Override
public void run() {
while(true) {
try {
Socket socket = cacheSocket.accept();
System.out.println("Accepted cache socket from: " + socket.getInetAddress());
Thread acceptor = new Thread(new CacheHandler(socket));
acceptor.start();
Main.debug();
System.gc();
} catch (IOException e) {
e.printStackTrace();
}
}
}
有人知道为什么内存使用量一直在增加吗?任何建议都将不胜感激。谢谢!
发布于 2018-06-03 00:40:05
也就是说,所有的关闭/销毁操作都应该在finally
子句中执行。那一个肯定会被执行的。
https://stackoverflow.com/questions/50658985
复制相似问题