0

这个问题是解决附加库动态加载问题的下一步。我有一些这样的:

public static void loadAttachProvider(String binPath) throws Exception {
    /*
     * If AttachProvider is already available now then propably we are in JDK
     * or path to attach.dll was specified as java.library.path on startup
     */
    if (isAttachProviderAvailable()) return;

    /*
     * In normall-use code I have generated binPath appropriate to platform (VM)
     * family and bitness (e.g. win32 or win64)
     */
    System.setProperty("java.library.path", binPath);

    // Reload library path hack
    Field sys = ClassLoader.class.getDeclared("sys_paths");
    sys.setAccessible(true);
    sys.set(null, null);

    // Here I want to be sure that AttachProvider is available
    //System.loadLibrary("attach"); <- I'm try this too, but it's not suffiecient
    if (!isAttachProviderAvailable()) {
        throw new IOException("AttachProvider not available");
    }
}

检查 AttachProvider 的可用性如下所示:

public static boolean isAttachProviderAvailable() {
    // This line is a substance of AttachProvider.providers() method
    ServiceLoader<AttachProvider> providers = ServiceLoader.load(AttachProvider.class, AttachProvider.class.getClassLoader());
    try {
        for (Iterator<AttachProvider> it = providers.iterator(); it.hasNext();) {
            /*
             * In normall-use code the "windows" constant is replaced
             * by something like platform-specific PLATFORM_FAMILY
             */
            if (it.next().type().equals("windows")) return true;
        }
    } catch (ServiceConfigurationError ex) {}
    return false;
}

如果您使用 JDK 的私有 JRE 运行它,那么一切都会好起来的,因为 JDKattach.dll在默认库路径中。

问题

仅当我删除第一次出现时,这才有效isAttachProviderAvailable,因为如果我尝试AttachProvider在它可用之前实例化,那么我无法在稍后attach.dll加载时实例化它。ServiceLoader不会根据新的库路径刷新。如何解决这个问题?如何在AttachProvider不实例化的情况下检查可用性或如何刷新ServiceLoader

4

1 回答 1

0

解决了第一个附加检查替换为如下内容:

try {
    System.loadLibrary("attach");
    if (isAttachProviderAvailable()) return;
    throw new IOException("AttachProvider not available");
} catch (UnsatisfiedLinkError ex) {
   /*
    * dll can't be loaded, so we need to specify special binpath
    * and reload library path as post above
    */
}

但是我正在等待更好的解决方案。

于 2012-06-26T14:46:37.027 回答