Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What are the consequences if we try to attach a Native Thread permanently to the DVM (JVM)?

Is it feasible to attach a native thread permanently to the JVM (AttachCurrentThread) (or) is it better to attach when ever required (calling java functions) and detach immediately once the work is done

I wrote a sample native app with the above cases, didn't find any difference. But by googling, vaguely I came to know that, when attached to JVM , JVMs thread scheduling is responsible for scheduling else OS will schedule the native thread (if not attached). Is this true?

It is important to detach any thread that has been previously attached; otherwise, the program will not exit when you call DestroyJavaVM. - http://java.sun.com/developer/onlineTraining/Programming/JDCBook/jniref.html#attach

Will there by any performance issues?
Please let me know if anyone knows, its one my important design aspect.

Thanks & Regards.

like image 561
Suman Avatar asked Dec 20 '11 12:12

Suman


2 Answers

Generally speaking, the main performance cost is the thread creation at OS level. Either the thread is creating natively and then attached or directly created as java.lang.Thread from Java API.

If you re-use the same native thread, performance will be good. By the way, do not create dozens of native threads.

The JVM does not schedule threads itself. It may force them in sleep state for various reason like garbage collection. In that specific case, it has to wait for a JNI call from a native thread before collecting. So you have to avoid too long code execution without JNI call to keep the VM heap consumption low.

Moreover, you have to take care to call DeleteLocalRef before detaching a native thread or else your VM will leak memory.

like image 142
Yves Martin Avatar answered Nov 04 '22 00:11

Yves Martin


When a native thread is attached permanently, not able to exit the native thread. Its crashing when we try exiting the native thread without detaching. But when we detached, native thread was able to do graceful exit.

like image 1
Suman Avatar answered Nov 04 '22 01:11

Suman