Is native method heavily used In JDK?

Here is a stack prompt for SocketException:

java.net.SocketException: Network is unreachable
    at java.net.PlainSocketImpl.socketConnect(Native Method)
    at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:345)
    at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:206)
    at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:188)

I noticed that PalinSocketImple.socketConnect is a native method. If I remember correctly, the read() method of InputStream is implemented in native, too. The execution of native method need lots of data type conversion, which may become a performance issue(I guess). All methods are finally implemented in a native way(call a native method). Is that correct?

Answer

It is entirely possible to write a program without ever invoking native code from the main or any other user created thread. The problem is that it wouldn’t be a very useful program. The JVM is just that, a virtual machine. It isolates the program from the underlying OS to provide platform independence. Native methods provide access to resources found outside of the virtual machine where your code is running.

All interactions with the OS have to happen in native code, since it is not possible for java code to directly interact with the OS. This includes IO, graphics, or even reading the current time. So yes, if your program does any type of interacting outside of the virtual machine, then it does so through native code.

Leave a Reply

Your email address will not be published. Required fields are marked *