Search code examples
javaclassloader

Should ClassLoader be thread-safe?


I'm writing my custom classloader, and am wondering if I should make it thread-safe? As you can easily see, not all native Java classloaders are thread-safe, only sun.misc.Launcher.AppClassLoader does (and yet, I've checked OpenJDK sources, and in OpenJDK it is not).

Is there a reason java classloaders are not synchronized? Should custom classloaders be thread-safe?


Solution

  • ClassLoader.loadClass() is synchronized.

    Typically a custom classloader won't override this method, but it might override findClass(). Since findClass() is called by loadClass and is therefore called from a synchronized critical section, it doesn't itself need to be synchronized.