0

I'd like to implement my own custom ClassLoader. Basically it should do exactly what the default OSGi ClassLoader does.

I am using Karaf/Felix, so in my case that's org.eclipse.osgi.internal.baseadaptor.DefaultClassLoader

The reason for implementing my own class loader is: I use JNI to load a DLL (with System.load()). But every time I redeploy my bundle I get a UnsatisfiedLinkError exception (Native Library xyz.dll already loaded in another classloader).

This is because the DLL is already loaded by the JVM - and stays as long as the ClassLoader that loaded it is NOT garbage collected.

So I want to do something like this:

CustomClassLoader cl = new CustomClassLoader();
Class ca = cl.findClass("myPackage.MyClass");
Object a = ca.newInstance();
Method p = ca.getMethod("myMethod");
p.invoke(a);
p = null;
ca = null;
a = null;
cl = null;
System.gc();

Hopefully after that the CustomClassLoader is garbage collected - and the DLL is unloaded from the container.

What I found strange: Even so each bundle has it's own ClassLoader, an osgi:uninstall <bundle> does not unload the DLL - which means that the bundles ClassLoader is still alive (and not garbage collected).

Heena Goyal
  • 382
  • 3
  • 17
Frizz
  • 2,524
  • 6
  • 31
  • 45
  • Also, I am not sure your claim about a classloader being garbage collected results in any shared objects (DLLs) loaded via the classloader being "unloaded" from the VM process. Do you have any documentation for this behavior? – BJ Hargrave Mar 19 '14 at 13:37
  • See for example this one: http://tech-tauk.blogspot.de/2009/11/issues-with-loading-native-libraries-in.html "Native libraries are unloaded by the JVM when the class loader that found the library is collected from the heap during garbage collection." – Frizz Mar 26 '14 at 08:45
  • That is a blog article and not authoritative. I was thinking of documentation from Oracle/OpenJDK on this issue. – BJ Hargrave Mar 31 '14 at 16:11

1 Answers1

2

You also asked this question on the Apache Felix users list. My answer there was to leverage the native code mechanism that OSGi provides, as this solves your problems without you having to mess with classloaders. The mechanism provided by OSGi specifically addresses the case of updating a bundle with native code, so it should solve your problem nicely.

Marcel Offermans
  • 3,313
  • 1
  • 15
  • 23