<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Varada M on Medium]]></title>
        <description><![CDATA[Stories by Varada M on Medium]]></description>
        <link>https://medium.com/@mvarada2000?source=rss-9e6129b94781------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*yaWFCa6qRTFJDUch</url>
            <title>Stories by Varada M on Medium</title>
            <link>https://medium.com/@mvarada2000?source=rss-9e6129b94781------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 16:36:21 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@mvarada2000/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[An Overview of the Java Native Interface (JNI) & Java Native Access (JNA)]]></title>
            <link>https://medium.com/@mvarada2000/an-overview-of-the-java-native-interface-jni-java-native-access-jna-63c2024b68be?source=rss-9e6129b94781------2</link>
            <guid isPermaLink="false">https://medium.com/p/63c2024b68be</guid>
            <category><![CDATA[jna]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[jni]]></category>
            <dc:creator><![CDATA[Varada M]]></dc:creator>
            <pubDate>Mon, 06 May 2024 11:07:13 GMT</pubDate>
            <atom:updated>2024-05-06T11:07:13.404Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8zQOVyF37-W5iOCWtqY2ag.jpeg" /></figure><blockquote>The fact that Java as a language is platform-independent and the Java Virtual Machine (JVM) is platform-dependent is really cool.</blockquote><p>Java programs can run anywhere where the Java platform is present, earning them the title “<em>write once, run anywhere</em>”. The host environment consists of the operating system, CPU instruction set and native libraries. A Java application is compiled into an intermediate code known as bytecode which is universal. JVM and bytecode combined give Java the status of platform independent. JVM then turns the bytecode into machine code. Machine code, as the name implies, is a language understood by the underlying operating system. This makes JVM <em>platform independent</em>.</p><blockquote>This raises a question. What happens when Java application requires to access system-specific functionality or native functionality which is not available in the standard java runtime? How does java address this issue? Here comes the role of <strong>Java Native Interface (JNI)</strong>.</blockquote><h4>Let’s know more about JNI</h4><p>The above question itself defines JNI. The Java Native Interface (JNI) is a connector that allows the JVM to interface with native functions or shared objects. This is accomplished through the invocation API.</p><h4>Example of how java code invoke a native method.</h4><p>Here is a simple program in java which invoke a method implemented in C code</p><p><strong><em>getrlimit() </em></strong>subroutine provides system resource limits used by the processes. For more information : <a href="https://www.ibm.com/docs/en/aix/7.2?topic=g-getrlimit-getrlimit64-setrlimit-setrlimit64-vlimit-subroutine">https://www.ibm.com/docs/en/aix/7.2?topic=g-getrlimit-getrlimit64-setrlimit-setrlimit64-vlimit-subroutine</a></p><p><em>We can declare native method in java code in this way</em> :</p><pre>//GetRLimit.java<br><br>public class GetRLimit {<br>    static {<br>        System.loadLibrary(&quot;getrlimit&quot;);<br>    }<br><br>    public static native int[] getrlimit();<br><br>    public static void main(String[] args) {<br>         int[] resources = getrlimit();<br>         for (int i = 0; i &lt; resources.length; i++) {<br>             System.out.println(&quot;Resources = &quot; + resources[i] + &quot;\n&quot;);<br>         }<br>    }<br>}</pre><p>In the above code, the main method invokes a method implemented in native code, <em>getrlimit()</em>. In order to invoke a native method in java, we use <em>native modifier.</em></p><p>Here, the native method <em>getrlimit()</em> is called in main() and it has to be loaded first. That’s why the <em>System.loadLibrary(“getrlimit”)</em> is implemented inside a static field. This makes sure that the native library is loaded before any method in the code is called.</p><p><em>The java code has to be compiled to produce GetRLimit.class</em></p><pre>// compile the java program<br>javac GetRLimit.java</pre><p><em>As a next step, we should create a shared object, libgetrlimit.so for UNIX or GetRLimit.dll for windows.</em></p><pre>// creates the header file GetRLimit.h<br>javah GetRLimit</pre><p><em>Native code implementation :</em></p><pre>// getrlimit.c<br><br>#include &lt;stdio.h&gt;<br>#include &lt;sys/time.h&gt;<br>#include &lt;sys/resource.h&gt;<br>#include &lt;jni.h&gt;<br>#include &lt;jni_md.h&gt;<br><br>#include &quot;GetRLimit.h&quot;<br><br>JNIEXPORT jintArray JNICALL <br>Java_GetRLimit_getrlimit(JNIEnv *env, jobject obj) {<br><br>    struct rlimit64 *RLP;<br>    struct rlimit64 lim;<br><br>    jint Resources[] = {RLIMIT_FSIZE, RLIMIT_NOFILE, RLIMIT_NPROC, <br>                             RLIMIT_RSS, RLIMIT_THREADS, RLIMIT_STACK};<br><br>    jintArray resourceLimits = (*env)-&gt;NewIntArray(env, 6);<br>    jint limits[6];<br>    <br>    jsize len = (*env)-&gt;GetArrayLength(env, resourceLimits);<br>    <br>    // Get Resource limit<br>    for (jint i = 0; i &lt; len; i++) {<br>        jint result = getrlimit64(Resources[i], RLP);<br>        limits[i] = (jint)lim.rlim_max;<br>        (*env)-&gt;SetIntArrayRegion(env, resourceLimits, 0, len, limits);<br>    }<br><br>    return resourceLimits;<br><br>}</pre><p><em>Compile the native code :</em></p><pre>// compile the c code (getrlimit.c)<br>// xlc compiler is used for AIX. gcc or clang is used for linux<br>xlc -q64 -o libgetrlimit.so -I$JAVA_HOME/include -I$JAVA_HOME/include/aix -G getrlimit.c</pre><p>After declaring native method in java and compiling it, we have to implement the native code. As a first step we generated a header file for GetRLimit.java using <em>javah</em>. Further, <em>getrlimit.c</em> is compiled and shared library is build, which is then loaded in java code.</p><blockquote>By the way, don’t forget to add the header file <strong>jni.h </strong>and <strong>GetRLimit.h</strong> in getrlimit.c. The header jni.h provides the native code implementations of native interface, native types and more. Whereas on the other hand, <strong>jni_md.h</strong> contains the machine-dependent typedefs for jbyte, jint and jlong.</blockquote><p><strong><em>What about the portability of java?</em></strong></p><p>The Java Native Interface (JNI) facilitates the integration of platform-specific native code with Java applications, enabling interactions with native libraries or functions. However, this introduces portability concerns as the implementation of these native components can vary across different platforms. For instance, on Linux and AIX, a shared object file may be represented as libgetrlimit.so, whereas on Windows, it takes the form of GetRLimit.dll. Such discrepancies underscore the need for careful consideration of portability when utilising JNI in Java development.</p><p>To address these concerns, it is imperative to adopt practices that promote portability and ensure compatibility across platforms. This can involve compiling the native code separately for each target platform, leveraging platform-specific configurations, and employing cross-platform libraries or frameworks. Importantly, the JNI should ensures binary compatibility. That is, the native library binary should run on different JVMs on same host environment without the need of recompilation.</p><h4>Data Types of JNI</h4><p>The key aspects of JNI is to facilitate the exchange of data between java code and native code. Understanding these data types is crucial in developing an efficient JNI based application. JNI provides mappings for Java data types to corresponding native data types. These JNI data types encompass primitive types, reference types, method and field IDs, strings and constants.</p><p><em>Primitive Types</em></p><p>There is not much difference between primitive type in java programming language and JNI. All the primitive types in JNI has well-defined sizes.</p><ul><li>jboolean — unsigned 8 bits</li><li>jtype — signed 8 bits</li><li>jchar — unsigned 16 bits</li><li>jshort — signed 16 bits</li><li>jint — signed 32 bits</li><li>jlong — signed 64 bits</li><li>jfloat — 32 bits</li><li>jdouble — 64 bits</li><li>void — not applicable</li></ul><p><em>Reference Types</em></p><p>There are different reference types which are organised in a hierarchy. In C programming language, all other JNI reference types are defined to be the same as jobject. JNI reference types provide a way for native code to interact with Java objects and perform operations on them. Some commonly used reference types :</p><ul><li>jobject (a reference to a Java object of any class)</li><li>jclass (java.lang.Class objects)</li><li>jstring (java.lang.String objects)</li><li>jarray (arrays)</li></ul><blockquote>jarray categorised into : jobjectArray (object arrays), jbooleanArray (boolean.arrays), jbyteArray (byte arrays), jcharArray (char arrays), jshortArray (short arrays), jintArray (int arrays), jlongArray (long arrays), jfloatArray (float arrays),jdoubleArray (double arrays)</blockquote><ul><li>jthrowable (java.lang.Throwable objects)</li></ul><blockquote>Native methods can access the java data types boolean, float, int, char etc. That is, boolean in java maps to jboolean of native language, similarly float gets mapped to jfloat and so on.</blockquote><p><em>For more information: </em><a href="https://docs.oracle.com/en/java/javase/22/docs/specs/jni/types.html#primitive-types"><em>https://docs.oracle.com/en/java/javase/22/docs/specs/jni/types.html#primitive-types</em></a></p><h3>Java Native Access (JNA)</h3><p>Even though JNI acts as bridge to call native libraries from our Java application, it brings its own layer of abstraction. For example, a JNI method needs a skeleton declaration at the Java side, and a stub implementation at the native side, with an array of primitives to manage the data passing across the brdige. In order to make a smooth transition to the native libraries without the need of a bridging native code, we can now use Java Native Access (JNA). That is, with JNA we can achieve the same goal by using java itself. In order to overcome the complexity caused by JNI, a third party open source library JNA has implemented.</p><p>JNA achieves the goal by libffi library. The libffi library makes it easy to call function from different programming language. With libffi, programmers can call any function described by a call interface at runtime. jna.boot.library.path contains the libraries to get loaded when a native class is accessed. If the required libraries is not present in jna.boot.library.path then JNA try to load it from system library path (System.loadLibrary()), for that jna.nosys should set to false. We can also get the native libraries from jna.jar , which contains the platform binaries.</p><blockquote>FFI stands for Foreign Function Interface, it provides an interface to call code from one language to another.</blockquote><p>Let’s see an example,</p><pre>//Example.java<br><br>import com.sun.jna.Library;<br>import com.sun.jna.Native;<br>import com.sun.jna.Pointer;<br><br>public class Example {<br>    public interface CLibrary extends Library {<br>        CLibrary INSTANCE = (CLibrary) Native.load(&quot;c&quot;, CLibrary.class);<br><br>        int getpid();<br>        int rand();<br>    }<br><br>    public static void main(String[] args) {<br>        int pid = CLibrary.INSTANCE.getpid();<br>        System.out.println(&quot;PID: &quot; + pid);<br><br>        int randNum = CLibrary.INSTANCE.rand();<br>        System.out.println(&quot;Random number: &quot; + randNum);<br>    }<br>}</pre><p><em>getpid()</em> function is used to retrieve the process ID of current process and <em>rand()</em> function to get a random number. CLibrary interface extends Library which defines a standard C library. The <em>getpid() and rand() </em>functions is called in this interface which represents the functions “<em>getpid() and rand()</em>” in C. These functions in C is loaded by using <em>Native.load()</em></p><h4>Summary</h4><p>Enabling a seamless way of integration between java and native code, JNI serves as vital bridge for two environments. This interface offers various data types, including primitive types, reference types, to facilitate the exchange of data between Java and native code. To make the whole process more simpler, JNA is used. JNA library enables us to make direct invocations of native methods from Java application. Overall, JNI and JNA plays a crucial role in enhancing the versatility and performance of Java applications by enabling interaction with native code.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=63c2024b68be" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[OpenJDK : Migration to Java 21]]></title>
            <link>https://medium.com/@mvarada2000/openjdk-migration-to-java-21-e71252859102?source=rss-9e6129b94781------2</link>
            <guid isPermaLink="false">https://medium.com/p/e71252859102</guid>
            <category><![CDATA[migration]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[openjdk]]></category>
            <dc:creator><![CDATA[Varada M]]></dc:creator>
            <pubDate>Sat, 16 Mar 2024 08:52:43 GMT</pubDate>
            <atom:updated>2024-03-16T10:15:11.701Z</atom:updated>
            <content:encoded><![CDATA[<h3>OpenJDK: Migration to Java 21</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*O3IlFbfARCNwmbtpap_OFg.jpeg" /></figure><p><em>Migration is never a new word for us. People migrate to access improved education, better economic opportunities and to experience a higher quality of life.</em> The same philosophy applies to software in general and Java in particular. OpenJDK, an open source implementation of Java has undergone huge transformation over the years. New features, enhancements to existing ones, bug fixes, security patches and serviceability capabilities were abundantly added as a result of large-scale collaborative development in the community. As a result, newer versions of Java exhibit better performance, security, diagnostics and stability compared to its predecessors.</p><h3><strong>Some new stories of JDK 21</strong></h3><h4>Few new JEPs of 21</h4><p><em>Record Patterns </em><a href="https://openjdk.org/jeps/440"><em>JEP 440</em></a></p><p>Record patterns deconstruct records into individual fields in a single declarative statement. This helps to work with a subset of a data collection with relative ease of access or reference, rather than using conventional indirections.</p><p><em>Pattern Matching for Switch </em><a href="https://openjdk.org/jeps/441"><em>JEP 441</em></a></p><p>Switch with pattern matching allows an expression to be evaluated with the given pattern. This helps improve expressiveness while doing complex data parsing.</p><p><em>Virtual Threads </em><a href="https://openjdk.org/jeps/444"><em>JEP 444</em></a></p><p>Virtual threads are threading simulations in the user space, so their life cycle operations are light-weight. This leads to an overall improvement in the throughput of highly concurrent applications.</p><p><em>Scoped Values (Preview) </em><a href="https://openjdk.org/jeps/446"><em>JEP 446</em></a></p><p>Scoped values provide a mechanism to share values between methods without parameterization and thread-local storage. This is best used with virtual threads wherein threading is simulated in the user space and a thread local is shared between all such threads.</p><h4>Deprecated APIs of JDK 21</h4><p>As we know, APIs evolve. At times, the usability of the field renders some APIs are inefficient, error-prone and vulnerable. So some APIs get deprecated and eventually get removed from the API set.</p><p>Many methods and classes have been removed in the lower versions of Java. Some of the noteworthy APIs are:</p><blockquote>Java.lang.Thread.stop()</blockquote><blockquote>Java.lang.Thread.destroy()</blockquote><blockquote>Applet APIs</blockquote><p>There are some APIs that are declared as deprecated in JDK 21:</p><pre>javax.management.remote.JMXConnector.getMBeanServerConnection(Subject)</pre><p>This method, which supports the legacy of Subject Delegation feature, relies on outdated APIs, which will be removed soon. Therefore, this method itself is deprecated and will not be replaced.</p><pre>javax.swing.plaf.synth.SynthLookAndFeel.load(URL)</pre><p>The APIs <a href="https://docs.oracle.com/en/java/javase/21/docs/api/java.desktop/javax/swing/plaf/synth/SynthLookAndFeel.html#load(java.io.InputStream,java.lang.Class)">load(InputStream, Class) </a>or <a href="https://docs.oracle.com/en/java/javase/21/docs/api/java.desktop/javax/swing/plaf/synth/SynthLookAndFeel.html#setStyleFactory(javax.swing.plaf.synth.SynthStyleFactory)">setStyleFactory(SynthStyleFactory) </a>will get removed in the future. “forRemoval = true” defined with these method implies the same.</p><p>For more information : <a href="https://docs.oracle.com/en/java/javase/21/docs/api/deprecated-list.html">JDK deprecated-list</a></p><h3>Steps For Migration</h3><p>1.<em> Download the JDK 21</em></p><p>§ As a first step, download the <a href="https://adoptium.net/temurin/releases/">JDK 21</a> with the suitable OS and architecture.</p><p>2. <em>Default charset</em></p><p>§ Charset is different for different JDKs. JDK 18 and later <em>supports UTF-18</em> and for the JDK 17 and previous versions, the default charset [<em>COMPAT</em>] is determined when the runtime starts, and it depends on the OS.</p><p>§ <strong><em>java -Dfile.encoding=CHARSET &lt;your application&gt;</em></strong> Set {CHARSET = UTF-8 or COMPAT} according to the need.</p><p>3. <em>Execute your program prior to compiling</em></p><p>§ While migrating to the new versions of java, it is imperative to remove deprecated APIs.</p><p>§ Warnings thrown by the VM can be for many reasons. VM may fail to start. In such a case, look for <a href="https://docs.oracle.com/en/java/javase/21/migrate/migrating-jdk-8-later-jdk-releases.html#GUID-977E1ED7-02BE-4A13-9B04-A719728E84BF">removed GC options</a>.</p><p>§ More importantly, we must have a better understanding of <a href="https://www.oracle.com/java/technologies/javase/21-relnote-issues.html#NewFeature">new features of JDK 21</a>.</p><p>§ Remember to upgrade the third party applications and libraries like Maven and Gradle that support the JDK 21.</p><p>4. <em>Java compilation</em></p><p>§ jdeps tool, a java class dependency analyser, gives warnings when we use internal APIs, JVM internal implementation like private and protected methods. [<a href="https://www.ibm.com/docs/en/semeruruntime-ce-z/11?topic=compatibility-determining-application-internal-apis">compatibility-determining-application-internal-apis</a>]</p><h3>Summary</h3><p>As we can see, if we are migrating from the immediate previous version of Java, the impact is minimal and the effort for migration is less. But as the gap between the source and destination versions of the migration increases, the efforts and impact increase. And their relation is not linear, but exponential. This is because as the gap increases, the general awareness and the literature around the migration path grows thin and vague. Hence it is strongly recommended to migrate your application as and when a new stable version is released!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e71252859102" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>