TIL – Native modifier in Java

While going through multithreading in java you must have came across this function “Thread.yield This function is special for me because the definition of the function is

public static native void yield()

So let’s go in detail about the native modifier

In Java, the native modifier is used to indicate that a method is implemented in a platform-specific manner, typically in a language other than Java, such as C or C++. This means that the method is not implemented in Java but rather in some other language, and that it uses system-level resources to perform its operations.

The Thread.yield() method. The yield() method is used to temporarily pause the execution of the currently running thread, allowing other threads to execute.

The Thread.yield() method is marked as native because it is implemented at the operating system level, and the JVM calls a platform-specific method to implement the yield() functionality.

public class YieldExample implements Runnable {
    public void run() {
        for (int i = 0; i < 5; i++) {
            System.out.println(Thread.currentThread().getName() + " running");
            Thread.yield();
        }
    }

    public static void main(String[] args) {
        YieldExample example = new YieldExample();
        Thread thread1 = new Thread(example, "Thread 1");
        Thread thread2 = new Thread(example, "Thread 2");

        thread1.start();
        thread2.start();
    }
}

In this example, we define a YieldExample class that implements the Runnable interface. The run() method is implemented to print the name of the current thread and call Thread.yield(), which pauses the current thread and allows other threads to execute.

We then create two threads, Thread 1 and Thread 2, and start them. When we run this code, the output will be something like:

Thread 1 running
Thread 2 running
Thread 1 running
Thread 2 running
Thread 1 running
Thread 2 running
Thread 1 running
Thread 2 running
Thread 1 running
Thread 2 running

As you can see, both threads are executing in parallel, and the Thread.yield() method is allowing them to switch execution periodically. Without the yield() method, one thread might dominate the execution time and prevent the other thread from executing. This is happening because OS specific implementation of yield method implemented by the JVM.

Related Post

Leave a Reply

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