I "fixed" a memory leak, but ... how best to fix it?

It was a very quick and temporary mistake. Bug fixed. It worked, but I would like to find a better understanding and solution.

It was a class constructor creating a leak

final transient  DataInputStream din;
final transient  DataOutputStream dout;
final transient  BufferedReader bin;
final transient  BufferedWriter bout;

NData(Socket sock0) throws IOException
    {
        sock=sock0;
        din= new DataInputStream(sock.getInputStream());
        dout = new DataOutputStream(sock.getOutputStream());
        bin = new BufferedReader(new InputStreamReader(din));
        bout = new BufferedWriter(new OutputStreamWriter(dout));
     //   .. 
    }

The bug fix was to change it (delete the final one) to allow me to assign zero later

transient  DataInputStream din;
transient  DataOutputStream dout;
transient  BufferedReader bin;
transient  BufferedWriter bout;

NData(Socket sock0) throws IOException
    {
        sock=sock0;
        din= new DataInputStream(sock.getInputStream());
        dout = new DataOutputStream(sock.getOutputStream());
        bin = new BufferedReader(new InputStreamReader(din));
        bout = new BufferedWriter(new OutputStreamWriter(dout));
     //   .. 
    } 

 //And to add a "magic" destructor

 void nuller() {
        din=null;
        dout=null;
        bin=null;
        bout=null;
    }

A method was completed that terminated the thread, closed the threads, so I added a call to the "nuller" method there, and the memory leak disappeared.

Why does it continue to allocate memory in "byte []" after the stream finishes and the stream closes? Why doesn't the GC throw it away? (except it is dirty with zero assignment)

EDIT:

According to casablanca, perhaps the NData object still exists, exists

final static ConcurrentHashMap <String,NData>(); 

NData , A remove (key) , , .. , .

HashMap ?

+3
3

"byte []"? GC ?

GC "" -, . , - NData. nuller - (din, dout ..), NData, , . , , , , .

:. , ? GC , . System.gc(), GC. , ConcurrentHashMap ( ) concurrency, , remove.

+4

, NData. NData ( - !). root.

, :

VisualVM, .

Eclipse Memory Analyzer ( ) , , .

, , ( !).

+3

In your nuller call bin.close () and bout.close () This will be done. Just make sure that nuller is called in the finally block somewhere, so it is always called.

+1
source

Source: https://habr.com/ru/post/1758065/


All Articles