Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sandbox for memory

Java supposed not to have memory leaks but it's still possible. When my program has memory leak I can fix it (I hope). But when some third party packages have it what can I do? Practically nothing except don't using this package.

Is there another solution? I like idea of sandbox. You are allowed to do whatever you want within some area and you "physical" don't have ability to bother other outside of your box. Is there way to create such sandbox for memory usage in Java? Imagine = create sandbox for memory usage, allow some package do whatever it does, take results and delete this sandbox with whatever garbage was left here! No complications with GC, no cleaning or disposition of memory. Just delete and forget about it.

Is there way to do so?

like image 782
Alex Avatar asked Nov 09 '22 13:11

Alex


1 Answers

The best way is to launch another JVM, communicate with it with socket(for example), and kill the JVM after it's done.

It'll be interesting to discuss whether we can sandbox it within the same JVM.

After you are done with using the 3rd party library, and you are no longer referencing any objects from that library, what could be the garbage that's still lingering?

  1. Their classes - even though you are not referening any of them, if they are loaded by the same classloader as your code, these classes will persist. And their static fields could reference more lingering data, and so forth

  2. ThreadLocal - it could have set some thread local variables, and not cleaned them up

  3. Thread - it could have spawned some threads that persist

  4. In some global place - e.g. System.setProperty() - it'll stay there.

So in general, it's probably difficult.

However, we can use a separate classloader and a separate thread to execute the 3rd party library, and this strategy can probably unload all garbages created by the 3rd party, in most cases.

Are there existing tools for doing that? I'm not too knowledgeable about that. I do have some experience with implementing a hot reloadable server, and I have some utility classes that can be used for this purpose. For example

// wrap 3rd party code, expose it as some java.*.* interface
public class MyWrapper implements Callable<String>
{
    @Override 
    public String call()
    {
        return ThirdParty.query(..);
    }
}



HotReloader hot = new HotReloader();
Callable<String> func = (Callable<String>)hot.getAppInstance("pkg.MyWrapper");
String result = func.call();
// then dereference `hot` and `func`

see HotReloader

like image 154
ZhongYu Avatar answered Nov 14 '22 23:11

ZhongYu