类加载过程是线程安全的吗?

答案是:是的。

ClassLoader.loadClass()源码:

Unless overridden, this method synchronizes on the result of  method during the entire class loading process.

除非是重写,那么这个整个加载过程都是同步的。

/**
     * Loads the class with the specified binary name.  The
     * default implementation of this method searches for classes in the
     * following order:
     *
     * 
    * *
  1. Invoke {@link #findLoadedClass(String)} to check if the class * has already been loaded.

  2. * *
  3. Invoke the {@link #loadClass(String) loadClass} method * on the parent class loader. If the parent is null the class * loader built-in to the virtual machine is used, instead.

  4. * *
  5. Invoke the {@link #findClass(String)} method to find the * class.

  6. * *
* *

If the class was found using the above steps, and the * resolve flag is true, this method will then invoke the {@link * #resolveClass(Class)} method on the resulting Class object. * *

Subclasses of ClassLoader are encouraged to override {@link * #findClass(String)}, rather than this method.

* *

Unless overridden, this method synchronizes on the result of * {@link #getClassLoadingLock getClassLoadingLock} method * during the entire class loading process. * * @param name * The binary name of the class * * @param resolve * If true then resolve the class * * @return The resulting Class object * * @throws ClassNotFoundException * If the class could not be found */ protected Class loadClass(String name, boolean resolve) throws ClassNotFoundException { synchronized (getClassLoadingLock(name)) { // First, check if the class has already been loaded Class c = findLoadedClass(name); if (c == null) { long t0 = System.nanoTime(); try { if (parent != null) { c = parent.loadClass(name, false); } else { c = findBootstrapClassOrNull(name); } } catch (ClassNotFoundException e) { // ClassNotFoundException thrown if class not found // from the non-null parent class loader } if (c == null) { // If still not found, then invoke findClass in order // to find the class. long t1 = System.nanoTime(); c = findClass(name); // this is the defining class loader; record the stats sun.misc.PerfCounter.getParentDelegationTime().addTime(t1 - t0); sun.misc.PerfCounter.getFindClassTime().addElapsedTimeFrom(t1); sun.misc.PerfCounter.getFindClasses().increment(); } } if (resolve) { resolveClass(c); } return c; } }

类加载过程是线程安全的吗?_第1张图片

你可能感兴趣的:(成神之路,java)