Force explicit deletion of a Java object
dealloc, garbage-collection, java
Solution
Looking at your code: are your `ObjectInput/OutputStream` instances newly created each time a packet arrives or is sent, and if so, are they closed properly? If not, do you call `reset()` after each read/write? The object stream classes keep a reference to all objects they have seen (in order to avoid resending the same object each time it is referred), preventing them from being garbage collected. I had that exact problem about 10 years ago - actually the first time I had to use a profiler to diagnose a memory leak...
Problem
I'm working on a Java server that handles a LOT of very dense traffic. The server accepts packets from clients (often many megabytes) and forwards them to other clients. The server never explicitly stores any of the incoming/outgoing packets. Yet the server continually runs into `OutOfMemoryException` exceptions. I added `System.gc()` into the message passing component of the server, hoping that memory would be freed. Additionally, I set the heap size of the JVM to a gigabyte. I'm still getting just as many exceptions. So my question is this: how can I make sure that the megabyte messages aren't being queued indefinitely (despite not being needed)? Is there a way for me to call "delete" on these objects to guarantee they are not using my heap space? ``` try { while (true) { int r = generator.nextInt(100);//generate a random number between 0 and 100 Object o =readFromServer.readObject(); sum++; // if the random number is larger than the drop rate, send the object to client, else //it will be dropped if (r > dropRate) { writeToClient.writeObject(o); writeToClient.flush(); numOfSend++; System.out.printf("No. %d send\n",sum); }//if }//while }//try ```