gpt4 book ai didi

java - PipedInputStream/PipedOutputStream 紧缩在 "loop"::为什么是 "java.lang.OutOfMemoryError: Java heap space"?

转载 作者:行者123 更新时间:2023-11-29 06:38:08 26 4
gpt4 key购买 nike

我正在试验 PipedInputStreamPipedOutputStream 并且无法理解为什么以下代码会导致 Java 堆耗尽问题。所有创建的 transient String 对象都应该被 gc 编辑。为什么我会收到 OutOfMemoryError

我正在尝试写入和读取 1000 个 String 对象,每个对象的长度为 100 万个字符。即使使用 -Xmx2g 调用,以下代码也会在大约一半时失败。更重要的是痕迹:

written string #453
read string #453
written string #454
Exception in thread "Thread-0" java.lang.OutOfMemoryError: Java heap space

... 表明 PipedInputStream 只是 PipedOutputStream“背后”的一个 String 对象。我不明白为什么垃圾收集未能回收所有必要的堆内存。

import java.io.*;
import java.util.*;


class Worker implements Runnable {

private ObjectOutputStream oos;
private PipedInputStream pis;

public Worker() throws IOException {
this.pis = new PipedInputStream();
this.oos = new ObjectOutputStream(new PipedOutputStream( pis ));
}

@Override
public void run() {
try {
for (int i = 0 ; i < 1000 ; i++) {
oos.writeObject(aBigString());
System.out.printf("written string #%d\n", i);
}
oos.flush();
oos.close();
} catch (IOException e) {
throw new RuntimeException(e.getMessage());
}
}

private static String aBigString() {
StringBuffer sb = new StringBuffer();
for (int i = 0 ; i < 1000*1000 ; i++)
sb.append("X");
return sb.toString();
}

public PipedInputStream getInput() {
return this.pis;
}
}


public class FooMain {
public static void main(String args[]) throws IOException, ClassNotFoundException {
Worker worker = new Worker();
(new Thread(worker)).start();
ObjectInputStream ois = new ObjectInputStream(worker.getInput());
String record = null;
int i = 0;
try {
while (true) {
record = (String) ois.readObject();
System.out.printf("read string #%d", i++);
}
} catch (EOFException e) {
ois.close();
System.out.println("done.");
}
}
}

最佳答案

这与管道流无关。您遇到了对象流的经典陷阱之一。为了保留对象的身份,流将保存通过它们的所有 对象。如果您需要将这些流用于大量对象,则需要定期调用 ObjectOutputStream 上的 reset()(但请注意,对象标识不会在重置期间保留电话)。

关于java - PipedInputStream/PipedOutputStream 紧缩在 "loop"::为什么是 "java.lang.OutOfMemoryError: Java heap space"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17167595/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com