Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JNI system.out and printf behaviour

I am writing a program that uses JNI to interface with a simple c program. I have created the following programs:

public static void main(String[] args) {
    Hello h = new Hello();
    System.out.println("before");
    int number = h.sayHello();
    System.out.println(number);
    System.out.println("after");
}

and

JNIEXPORT int JNICALL Java_Hello_sayHello (JNIEnv *env, jobject obj) {
     printf("Hello JNI\n");
     return 10;
}

To my surprise this program returns:

before
10
after
Hello JNI

To me this is very strange because it is clear that the c program is executed between the "before" and "after" statement (The number 10 is printed). But why is the printf statement not executed when it is called. Is it somehow blocked by the jvm because only one program is allowed to write to the output at the same time? Is there a way to correct this behavior?

like image 602
Maurice Avatar asked Apr 15 '14 13:04

Maurice


People also ask

What is JNI and how it works?

JNI is the Java Native Interface. It defines a way for the bytecode that Android compiles from managed code (written in the Java or Kotlin programming languages) to interact with native code (written in C/C++).

What is JNA vs JNI?

Java Native Access (JNA) is a community-developed library that provides Java programs easy access to native shared libraries without using the Java Native Interface (JNI). JNA's design aims to provide native access in a natural way with a minimum of effort. Unlike JNI, no boilerplate or generated glue code is required.

Is JNI fast?

When talking about JNI, there are two directions: java calling C++, and C++ calling java. Java calling C++ (or C) via the "native" keyword is very fast, around 50 clock cycles. However, C++ calling Java is somewhat slow.

What is JNI environment?

The JNI is a native programming interface. It allows Java code that runs inside a Java Virtual Machine (VM) to interoperate with applications and libraries written in other programming languages, such as C, C++, and assembly.


1 Answers

Yes. You will need to call flush.

In C, that is the fflush call -

printf("Hello JNI\n");
fflush(stdout);
return 10;

In Java, that is just flush on the Stream -

System.out.println("before");
System.out.flush();
like image 164
Elliott Frisch Avatar answered Oct 16 '22 02:10

Elliott Frisch