简体   繁体   中英

Java memory usage - is this syntax correct or it will cause a memory leak?

HashMap obj = new HashMap();
for(int i=0;i<1000;i++) {
    obj = getObjects(i);
}

Will this code cause a memory leak at this line "obj = getObjects(i);"?

I'm not sure if the old values of obj are released or if they are still using the memory.

If this is a memory leak what is the correct syntax?

In java there is a garbage collector, so using normal operations like this it is pretty hard to cause a memory leak. The garbage collector goes around freeing any memory that is no longer referenced.

More info on garbage collection: http://www.oracle.com/webfolder/technetwork/tutorials/obe/java/gc01/index.html

The short answer is that your code should not cause a memory leak.

A reference or object is not "released" when it is overwritten. There is no more work in assigning a reference as assigning one int to a variable.

Instead the the old reference simply no longer exists, and GC looks for references which still exist.

Will this code cause a memory leak at this line "obj = getObjects(i);"?

It is impossible to say for sure. You haven't shown us the code for getObjects , and it is possible (though not likely, based on the method's name) that that method could have an internal memory leak.

However, repeatedly assigning references to a simple variable (eg obj ) will not leak memory.

I'm not sure if the old values of obj are released or if they are still using the memory.

It is not as simple at that:

  • From a storage management perspective, the "old values of obj" are references ... not objects.
  • The objects that those references refer to will not be released immediately when you assign a different reference to obj .
  • They will eventually be released in the future by the GC, provided that:
    • there is sufficient memory pressure to cause the GC to run for the "space" where the objects have been allocated, and
    • nothing else references the objects.

If this is a memory leak what is the correct syntax?

For the record, memory leaks are not a syntax issue.

I made a test and is fine, java is periodicaly releasing memory. I still used HashMap to reproduce my application context.

package memtest;

import java.util.HashMap;

public class MemTest {
    public static void main(String[] args) throws InterruptedException {
        HashMap obj = new HashMap();
        int loop = 1;
        while(true) {
            HashMap newObj = new HashMap();
            newObj.put("1", "big string that is not pasted here");
            obj = newObj;
            System.err.println("At loop "+loop);
            Thread.sleep(1000);
            loop++;
        }
    }    
}

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM