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?
- Is there something fundamentally wrong with decorating your IO stream multiple times?
- Is it better to decorate a stream on demand, before actually using it, and then let the garbage collector handle it when its no longer needed?
- As an extension to the above question, before when everything was working without memory errors, the only object I actually stored was OOS. Yet, now, the memory errors are related to OOS. Does the creation of DOS or OS cause the garbage collector to not run properly?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…