本地方法接口
本地方法接口即JNI(Java Native Interface),其作用是调用非Java代码实现的方法。之所以会出现JNI,是因为有些操作Java语言层面无法做到,需要其它的语言来操作。java是跨平台的语言,既然是跨了平台,所付出的代价就是牺牲一些对底层的控制,而java要实现对底层的控制,就需要一些其他语言的帮助。比如Java语言层面是无法启动一个线程的,这需要借助底层C++来实现:
public synchronized void start() {/*** This method is not invoked for the main method thread or "system"* group threads created/set up by the VM. Any new functionality added* to this method in the future may have to also be added to the VM.** A zero status value corresponds to state "NEW".*/if (threadStatus != 0)throw new IllegalThreadStateException();/* Notify the group that this thread is about to be started* so that it can be added to the group's list of threads* and the group's unstarted count can be decremented. */group.add(this);boolean started = false;try {start0();started = true;} finally {try {if (!started) {group.threadStartFailed(this);}} catch (Throwable ignore) {/* do nothing. If start0 threw a Throwable thenit will be passed up the call stack */}}}private native void start0();
而其中的native关键词就是代表该方法的实现代码是非Java代码, 该方法是一个原生态方法,方法对应的实现不是在当前文件,而是在用其他语言(如C和C++)实现的文件中 。 这个特征并非java所特有,很多其它的编程语言都有这一机制,比如在C++中,你可以用extern “C”告知C++编译器去调用一个C的函数。在定义一个native method时,并不提供实现体(看起来像定义一个接口),因为其实现体是由非java语言在外面实现的。 标识符native可以与所有其它的java标识符连用,但是abstract除外。这是因为native暗示这些方法是有实现体的,只不过这些实现体是非java的,但是abstract却显然的指明这些方法无实现体。一个native method方法可以返回任何java类型,包括非基本类型,而且同样可以进行异常控制。这些方法的实现体可以自制一个异常并且将其抛出,这一点与java的方法非常相似。
其实, 目前该方法使用的越来越少了,除非是与硬件有关的应用,比如:通过java程序驱动打印机或者Java系统管理生产设备,在企业级应用中已经比较少见。
本地方法栈
本地方法栈即Native Method Stack,该栈用于登记native方法,因此不能登记非native方法外的方法,用于管理native方法的调用。本地方法和Java栈具有相同的特点,满足后进先出、线程私有、也会抛出
StackOverflowError 和 OutOfMemoryError 异常……
