0

I am currently experiencing a memory leak in my code, and I have a gut feeling it's because of the multiple times I'm getting instance of a class without actually closing it, causing many many instances of the class. So my question is, is there any way I can close the instance of the class I'm getting? I'm getting the instance like such: public static MyClass getInstance() { return new MyClass(); }

And then I'll get instance of the class by doing: MyClass instance = MyClass.getInstance();

So I suppose what I'm asking for is if there is something like a .close(); method to close my instance.

Thanks.

TheCoder24
  • 37
  • 1
  • 1
  • 9
  • 1
    Garbage collection exists specifically so you don't have to do this to free memory. – user2357112 Apr 17 '15 at 01:48
  • can you provide some more code? just the fact that you are creating objects isn't going to give you a memory leak. – Camilo Casadiego Apr 17 '15 at 01:48
  • Post the rest of your code, there isn't enough here except to see you've implemented a factory/builder pattern. – Elliott Frisch Apr 17 '15 at 01:49
  • well I'm not sure if this is causing the memory leaks, just want to try and see if it is, would changing the value of the instance to null close it? – TheCoder24 Apr 17 '15 at 01:51
  • How many times are you calling `getInstance()`? Are you calling it within loops? Maybe it's best if you return a pre-created instance. – Vince Apr 17 '15 at 02:07

1 Answers1

0

Java has an automatic garbage collector, so if you no longer reference an object, it will be deleted from memory.

You might accidentaly be storing references, or storing too many at once or some other problem.

Also don't debug by gut instict, stick a profiler or debugger in there and figure out where your memory leak is coming from! Good luck!

Anubian Noob
  • 13,426
  • 6
  • 53
  • 75
  • If it removes any unused memory, than how is a memory leak formed, somewhat confused. – TheCoder24 Apr 17 '15 at 02:01
  • Well if you stored references it's still counted as used memory. It's actually somewhat difficult to create a memory leak in Java. Check out this question: http://stackoverflow.com/questions/6470651/creating-a-memory-leak-with-java – Anubian Noob Apr 17 '15 at 02:03