java 释放 system.load,如何避免两次调用System.load?

I have a class that calls a native function to get information about a system from its CMOS. The class has a static initialization block which loads the library containing the native function, and it looks something like this:

package lib.sysid;

public class SysId

{

private static native int getSysIdNative();

private static final String SYS_ID_PATH = "libsysid.so";

static

{

System.load(SYS_ID_PATH);

}

public static int getSysIdFromCMOS()

{

int returnValue = getSysIdNative();

}

}

According to my testing, the method works fine the first time I use it, but if I call the method again at a later time, the static initialization block also runs, causing an UnsatisfiedLinkError:

java.lang.UnsatisfiedLinkError: Native Library libsysid.so already loaded in another classloader

How can I avoid the static initialization block from executing the System.load() method if it has already been run?

Alternatively, is there a way for me to attempt to "unload" the library if it is already loaded before calling the System.load() method again?

EDIT: Strangely enough, if I surround the System.load() call with a try-catch block, I still get an UnsatisfiedLinkError, but this time it comes from the actual call to getSysIdNative(). The error I see is the following:

lib.sysid.SysId.getSysIdNative()I

What the heck is that "I" that shows up? I've tried to attach a debugger to this code to see where the message gets populated, but so far I haven't been successful.

解决方案

Just a guess, but I think the only way for a single JVM to load a class (and execute its static initializers) twice is to load it with different classloaders. So there may be a second classloader involved here that you're not aware of. This would apply if a different (set of) classloader(s) is in effect the second time around.

Under a "real" operating system, java -verbose:class would give you loader messages to verify this with. I'm not sure how you'd go about verifying this on an embedded system. You could modify getSysId() to print (?) or somehow dump a reference to SysId.class.getClassLoader().

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值