This question may seem a little trivial at first, but I am experiencing odd OutOfMemory problems since I began implementing this. After looking through the Java Heap Dumps, I know the memory leak is related to the ObjectOutputStream variable. Without further ado, here is the code:
In my constructor, I am setting up field variables that will hold my Input/Output Stream variables. Along with it, I am creating two other sets of variables for when I am specifically doing IO on custom objects and then pure primitives:
public SingleServer(Socket s, int maxThreads) {
client = s;
serversCreated.incrementAndGet();
try {
is = client.getInputStream();
os = client.getOutputStream();
ois = new ObjectInputStream(is);
oos = new ObjectOutputStream(os);
dis = new DataInputStream(is);
dos = new DataOutputStream(os);
} catch (Exception e) {
// ...
}
print("Client Connected");
}
Now, before, all there was was storage of OOS, the object output stream. So, you may have asking why I am going through the trouble of creating these fields? The answer is I wanted to separate the sending of primitives from the sending of custom objects vs the sending of pure bytes. I thought Java was okay in separating things out like this.
What I am noticing is that suddenly and hard-to-predictingly some objects now cause OutOfMemory Error's which crash my program. I know I can just forget about using all these different decorators for the IO classes, but I want to understand why these out of memory errors would happen?
Wrapping the same InputStream
in two independent wrappers is an unsupported idiom. The first wrapper might immediately read some input to fill its buffer; the second one may try to do the same. Each wrapper is free (and even encouraged) to assume that it can fully read out its underlying stream, at its own discretion.
So, in a nutshell,
Is there something fundamentally wrong with decorating your IO stream multiple times?
Yes, there is.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.