设置ClassLoader的开销

时间:2014-05-12 19:01:29

标签: java performance classloader

通过以下方式更改ClassLoader是否有开销:

Thread.currentThread().setContextClassLoader(otherClassLoader);

在需要隔离的ClassLoader的方法调用之前和之后更改ClassLoader是否会被视为不良做法,例如:

public class CallsThingsInIsolatedClassLoader {
  // Set these references when the ClassLoaders are built
  public static ClassLoader isolatedClassLoader;
  public static ClassLoader normalClassLoader;


  public static Object getResult() {
    Object result = null;
    Thread.currentThread().setContextClassLoader(isolatedClassLoader);
    result = Foo.getResult(); // Call method which requires an isolated ClassLoader.
    Thread.currentThread.setContextClassLoader(normalClassLoader);
    return result;
  }

这会引起任何性能问题吗?保留类似线程池的东西来调用需要隔离的ClassLoader的方法,以避免切换ClassLoader会更好吗?

1 个答案:

答案 0 :(得分:0)

source code表示为线程设置不同的类加载器的开销很小。重复调用可能会导致性能问题(本机方法currentThread()也不是免费的),但必须大量使用。

在需要它的方法调用之前和之后更改ClassLoader是不错的做法,但不保证恢复原始ClassLoader是不好的做法。换句话说,始终使用finally子句来恢复原始的ClassLoader:

    final Thread currentThread = Thread.currentThread();
    final ClassLoader orgCl = currentThread.getContextClassLoader();
    Object result = null;
    currentThread.setContextClassLoader(myCl);
    try {
        result = Foo.getResult();
    } finally {
        currentThread.setContextClassLoader(orgCl);
    }