0

I'm using a third library in Java which a uses a singleton pattern. After using this library for a short time I no longer need this library and ready to free it, but because it uses a singleton pattern and doesn't supply any clean/free/close method which cleanup the allocated memory will keep in the heap as long as my application is running.

My question is: can I clean memory that was allocated for this library even if it doesn't supply any function for this?

galvan
  • 7,400
  • 7
  • 38
  • 55
  • In general, no. Are you able to run the library code in a separate process, so that all of the memory would be cleaned up when that terminates? – Andy Turner Mar 31 '15 at 11:30
  • @AndyTurner, just want to know, why no? so, even let say, i set the reference to null, the reference will still not be able to be cleaned by gc? – kucing_terbang Mar 31 '15 at 11:33
  • @kucing_terbang In answer to the question "can *I* clean memory", no. You can't force the memory to be reclaimed by GC. You can't even guarantee that it can *ever* be reclaimed by GC, since the library might hold on to references that you can't see. – Andy Turner Mar 31 '15 at 11:36
  • you can try and use refelection to get the "instance"-field of the singleton, make it accessible and assign "null": Field f = MailManager.class.getDeclaredField("instance"); f.setAccessible(true); f.set(null, null); – fiffy Mar 31 '15 at 11:39
  • @AndyTurner hmmm. Interesting.. do you have a reference to what you said? maybe a link to a doc or your experiment? that would be great. – kucing_terbang Mar 31 '15 at 11:52
  • Using reflection as @fiffy says can help in this? – galvan Mar 31 '15 at 11:54
  • @kucing_terbang I don't really know what you're looking for. It is [well known](http://stackoverflow.com/questions/1481178/forcing-garbage-collection-in-java) that you can't really force a garbage collection, only hint that you'd like one; and how can you know all of the references held by the library that you'd need to null out in order to allow them to be GC'd? – Andy Turner Mar 31 '15 at 12:04
  • @AndyTurner ouch, I think we are not on the same page here. I thought you were talking about the gc cannot clean up an object that which has no reference anymore. – kucing_terbang Mar 31 '15 at 12:18

0 Answers0