How to run a library in a "sandbox" mode using Java?

551 Views Asked by At

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?

1

There are 1 best solutions below

0
bmargulies On

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.