2

I'm using some third party source code, which is meant to be run with a GUI, but I'm integrating it without using the GUI, and I've noticed severe memory leaks from the third party code which I am using. So I'm wondering, would it be possible to somehow create an object of that third party application instance in something like a sandbox, where I could remove the object later and all the references to any objects that that code was calling would be removed by the garbage collector.

Is something like that possible? What alternatives are there to achieving a similar scenario or would like the only possibility be to call the other application from a process builder like java -jar customApp ...? That's a bit ugly though...

EDIT: Would running that code in a separate Thread and then wait for the thread to complete cause the garbage collector to remove all the objects related to what was called there?

Arturas M
  • 4,120
  • 18
  • 50
  • 80
  • You can certainly wrap that native code in an object of your own making, but that won't prevent it from leaking memory. The GC has no way of dealing with memory allocated by native code. – duffymo Aug 28 '16 at 20:44
  • I don't think this is reliable at the moment. You'd have to be able to unload the class objects as well, and I don't think a JVM can do that in all situations. Best just to find a library that doesn't have memory leaks. (And if you mean a native library instead of a Java library, then yes all bets are definitely off.) – markspace Aug 28 '16 at 20:44

1 Answers1

1

First, until you have actually studied the memory usage situation with a memory profiler (e.g. yourkit) and completely understood the reason for the memory consumption, you are unlikely to succeed in taming it.

Second, if native, rather than Java, memory is the issue, there's nothing to be done at all.

The following might approximate your desire.

Load the problematic library into its own class loader, and only reference it through a very narrow interface that you load in your main class loader and then inherit into the special class loader. This will make it much harder for references to be retained to objects created in the library, but by no means impossible. If the library creates threads, and puts references into ThreadLocal objects, for example, you're right back where you started, unless you can tell it to kill the threads. Still, if the library stacks up tons of objects in static references, this won't help.

bmargulies
  • 97,814
  • 39
  • 186
  • 310