1

I have a class that holds some big objects:

public class MyClass {

    BigObject bo;

    public MyClass() { ... }
}

Should i make a close method like the following:

public void close() {
    bo = null;
}

I think this is good for garbage collection (?) Am I on the right track? How should I approach the cleanup of this classes?

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
Twinone
  • 2,949
  • 4
  • 28
  • 39
  • 3
    No, its unnecessary. Just let it go out of scope. – Lucas Mar 26 '13 at 20:15
  • See also http://stackoverflow.com/questions/1481178/forcing-garbage-collection-in-java – Bizmarck Mar 26 '13 at 20:16
  • in Java don't think about clean up of the objects.Java will handle it for you. You don't even have control on garbage collection part. However making object null can be good idea if you don't want any part of the software to access object anymore – Addict Mar 26 '13 at 20:21

2 Answers2

4

I think this is good for garbage collection

Nope, it just makes the code messier.

What's going to hold a reference to the instance of MyClass? If you genuinely need the instance of MyClass to stay alive, but not the BigObject, then - and only then - should you bother setting bo to null. But at the same time, you should also consider your design. Usually, all of the state of a class is important to it for its whole lifetime. There are exceptions to that rule, but they're relatively rare.

When the instance of MyClass is eligible for garbage collection, the value of its bo variable will be irrelevant to whether the instance of BigObject is eligible for garbage collection, so it doesn't matter whether or not it's been set to null... but it does make a big difference in terms of the amount of code you end up not having to write trying to manually clean up after yourself.

You should clean up resources such as streams, native handles etc - but generally you can let the garbage collector handle memory.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
0

As soon as you lose the reference to the outer MyClass object, the inner BigObject reference is automatically understood to be uncreachable so it makes no difference to the Garbage Collector whether it is null or not. Do not clutter your codebase with such unnecessary code; write the code that fully leverages the benefits and services of the sophisticated garbage collection subsystem in Java.

Marko Topolnik
  • 195,646
  • 29
  • 319
  • 436