Can using too many static variables cause a memory leak in Java?

94

Solution 1

Static methods are just methods, they are not stored on the heap, they just don't get to use a "this" parameter.

Static variables serve as "roots" to the GC. As a result, unless you explicitly set them to null, they will live as long as the program lives, and so is everything reachable from them.

A situation is only considered a memory leak if you intend for the memory to become free and it doesn't become free. If you intend for your static variable to contain a reference to an object for part of the time, and you forget to set it to null when you're done with that object, you would likely end up with a leak. However, if you put it in the static variable and intend for it to be there for as long as the program is running, then it is most definitely not a leak, it is more likely a "permanent singleton". If the object got reclaimed while you wanted it to still exist, that would have been very bad.

As for your question about the heap: All objects in Java exist either on the heap or on the stack. Objects are created on the heap with the new operator. A reference is then attached to them. If the reference becomes null or falls out of scope (e.g., end of block), the GC realizes that there is no way to reach that object ever again and reclaims it. If your reference is in a static variable, it never falls out of scope but you can still set it to null or to another object.

Solution 2

If you have a static hashmap and you add data to it... the data will never disappear and you have a leak - in case you do not need the data anymore. If you need the data, it is not a leak, but a huge pile of memory hanging around.

Solution 3

Objects directly or indirectly referenced by statics will remain on the heap until the appropriate class loader can be collected. There are cases (ThreadLocal, for instance) where other objects indirectly reference the class loader causing it to remain uncollected.

If you have a static List, say, and add references to it dynamically, then you can very easily end up with "object lifetime contention issues". Avoid mutable statics for many reasons.

Solution 4

As long as you can reference these variables from somewhere in the code it can't by GCed which means that they will be there until the end of the application.

Can you call it a memory leak, I wouldn't call it a memory leak, usually a memory leak is memory that you normally expect to recover but you never do, or you only recover part of it. Also memory leaks usually get worse in time (eg: every time you call a method more memory is "leaked") however in this case the memory usage for those variables is (kind of) static.

Solution 5

It won't cause a memory leak in the classic C sense... For example

Class A{

static B foo;

...

static void makeFoo(){
   foo = new B();
   foo = new B();
}

In this case, a call to makeFoo() won't result in a memory leak, as the first instance can be garbage collected.

Share:
94
James Yang
Author by

James Yang

Updated on July 09, 2022

Comments

  • James Yang
    James Yang almost 2 years

    Explicitly using String::from in the following code works, but how can I make it automatically use From<OsStringWrap<'a>> trait without explicitly using String::from?

    use serde::Serialize; // 1.0.115
    
    struct OsStringWrap<'a>(&'a std::ffi::OsString);
    impl<'a> From<OsStringWrap<'a>> for String {
        fn from(s: OsStringWrap) -> String {
            s.0.to_string_lossy().to_string()
        }
    }
    
    pub fn insert<T: Serialize + ?Sized, S: Into<String>>(_key: S, _value: &T) {}
    
    fn main() {
        for (key, value) in std::env::vars_os() {
            // HOW-TO: auto use From<OsStringWrap<'a>> trait
            // without explicit `String::from` like below?
            /*
                insert(OsStringWrap(&key), &OsStringWrap(&value))
            */
    
            // below using `String::from` to make it explicitly
            // but want to find a way to make it shorter
            insert(OsStringWrap(&key), &String::from(OsStringWrap(&value)))
        }
    }
    

    Playground, and the insert method is a real case from tera

    • Shepmaster
      Shepmaster over 3 years
    • Shepmaster
      Shepmaster over 3 years
      Why does this code use Serialize? That doesn't seem important to the question.
    • James Yang
      James Yang over 3 years
      @Shepmaster the insert method is a real case from tera
    • trent
      trent over 3 years
      So you have a function that requests a T: Serialize... and rather than implementing Serialize for OsStringWrap you are converting it to a String first... and you want the String-conversion to be automatic? Seems roundabout. Why not just implement Serialize?