Notifying java object from C/C++ code? - java

I am wondering is it possible to notify( notify() ) a java object with native code?
For example let's say we have a thread in java which is waiting for a signal as below.
void _do_something() throws Exception{
synchronized(__lock_){
__lock_.wait();
}
}
Then is it possible to notify the __lock_ object from a native code?!
Should I pass the __lock_ object to the c code? so how and how C code call the notify() method.
Any help is appreciated.
Thanks in advance.

This is very doable from native code. You need to use JNI though...
Then is it possible to notify the _lock object from a native code?!
Sure, as long as your native code has a handle to the _lock object, all you have to do is to synchronize and call notify on it (like you would call any other java object from native code).
Should I pass the _lock object to the c code?
Yes. Both because you need it when you call the CallVoidMethod() JNI function to call notify() but also because you need to enter/exit Monitor of that object (the JNI equivalent way of saying "synchronized(_lock)"
so how and how C code call the notify() method
First you need to understand the basics of mapping your native code to something you can call from java. Then you need to understand how to call back into java from that native code and when you understand that, it is all a matter of learning how to use MonitorEnter, CallVoidMethod and MonitorExit.
Unfortunately, JNI sometimes seems to be designed to keep people away. When you're new at it, it is kind of hard to do proper debugging. I would recommend to start small to get a grip of it and wait with the real stuff until you understand the basics.
My best advice with JNI is to stick to the rules (at least in the beginning), check exceptions after every call (and dump them to stderr or something when you get them) and run your java with -Xcheck:jni.
There are plenty of tutorials around, I found this one in the top10-list when I googled, it seems ok.
Good luck!

Related

Java What Happens When a Thread is Started Until It Starts Running

What is the sequence of events that occur between calling Thread.start and Thread.run being called? I ask because mostly out of curiosity, and because I can't seem to trace the native calls to find their implementation, but also to answer some questions I had about what I can expect after starting a Thread.
This question gives a good high level answer, but I'm looking for a more in-depth answer + links to source code is possible.
I'm not sure how every native method of a Java Thread is hooked up, but Java Threads use pthreads in the native layer. https://en.wikipedia.org/wiki/POSIX_Threads
The Thread#start method in Java creates (and starts) a VMThread, which is backed by a pthread. The VMThread is backed by JNI and most of its calls wind up at vm/Thread.c (e.g. https://android.googlesource.com/platform/dalvik/+/eclair-release/vm/Thread.c).
E.g. the VMThread#create calls JNI method Dalvik_java_lang_VMThread_create and that calls the dvmCreateInterpThread function in vm/Thread.c
I hope this is a good start for you to start Googling around what exactly happens between Thread creation and its start.
Streets of Boston pointed me in the right direction, where I found https://android.googlesource.com/platform/art/+/marshmallow-release/runtime/ . I will update this answer as soon as I get a chance to read through the code and grok it.

Signals in Java

I was use C++ signals
sigaction
struct sigaction sigact;
and set all attributes to use signals
now I want to use it in Java what's the equivalent in java
to the include "signal.h"
I have two threads:
one run from the beginning of the program
and the other run at the signal Alarm
I was implement the functionality in C++ using Signals as shown and now I want to implement it using java
Edited to put my Goal:
actually my Goal to run the second Thread When the signal arrives from the first thread
Thus sounds like a typical "XY-Problem".
In plain Java you have no access to OS-signal. They are platform specific and Java strifes to be platform agnostic. Also: calling Java from a signal handler with JNI might be "fun" (as explained in Dwarf Fortress).
So you have to go back to the drawing board and think about what is the problem you want to solve and stop thinking about how to solve it with signals.
That said: if you insist on signals and are not afraid to use internal stuff which might change on a whim: Take a look at sun.misc.Signal.
EDIT Now the question made it clear, that the signalling takes place within one JVM. For this signals are definitely the wrong thing in Java.
So the simplest solution is to create and start the second thread directly from within the first thread. No signalling required.
The next best solution is to code a "rendezvous point" using Object.wait() in the second thread (using any object instance but the Thread itself) and Object.notify() or notifyAll() from the first thread. Searching for these terms in a Java tutorial will bring up enough examples.

Attaching third party thread to vm when using jni

I'm writing a Java program that uses a hardware driver written in c. This hardware driver starts a callback thread, and you can register callback functions to be called when stuff happens. How can I attach this thread to the jvm so that it can call the Java methods for these callbacks? I only have the thread id returned from the start_callbacks() function, returned as an int, but it is the pthread_t used in the call to pthread_create().
One way I found is to use pthread_once on the start of every callback function and attach the thread there. But then there is no way to detach it. I tried to use pthread_cleanup_push/pop, but they need to be called as a pair so that didn't work.
It seems to me that my only option to do this right is to attach and detach the thread at every callback call. Or rewrite the driver somewhat, which I really don't want to do.
Is there something I missed?
That's exactly what the JNI calls AttachCurrentThread() and DetachCurrentThread() are for.
The solution to you problem can be resolved with thread_local storage (C++ 11 and higher). This allows you to attach to an arbitrary thread, and then it will automatically detach when the thread exist (even when you didn't create the thread and have no control over it's life cycle).
A sample example of how to implement that in C++ can be found in my answer here:
https://stackoverflow.com/a/59934966/8367574

Detecting thread interruption with JNA native wait call (Windows)

I'm trying to write some code that performs a wait via JNA (e.g. by calling the Kernel32 function WaitForSingleObject), but I'd also like the wait to finish if Thread.interrupt() is called; I assume Java uses something like an Event object to implement interruption; is there any way of getting the Event from Java in order to use it in a call to WaitForMultipleObjects? Or is there any other way I could arrange for my wait to finish if the thread is interrupted?
Java supports it via NIO and very few people are aware of, the class in question is abstract but that's no issue:
java.nio.channels.spi.AbstractInterruptibleChannel. It has 3 methods of interest: begin() and end(), those are final, plus that one you have to implement: "protected abstract void implCloseChannel() throws IOException"
The method is going to be called from the thread invoking interrupt(), so be careful.
The use is very simple: call begin before entering the native code and end() upon return. Handling the interruption in implCloseChannel.
Happy coding!
Having found a bit of time to do some more research, I went for a digging expedition in the OpenJDK source code this morning. It turns out that starting with the native implementation was wrong; there's a pure-Java mechanism for doing this.
The class sun.misc.SharedSecrets has a static method getJavaLangAccess(), which returns an object with a method blockedOn(Thread, sun.nio.ch.Interruptible). This can be used to arrange for Thread.interrupt() to call a method supplied by one of my own objects, at which point I can create my own interruption Event object with which I can ensure waits are terminated as required.
Doing this introduces dependencies on sun's implementation of the Java class library, but probably less so than digging through the JVM's native state to try to extract an event handle that it uses internally.

JNI Global Static Variables in C++ Code

I have a JNI C++ code being called from a multi-threaded java application
This C++ code has 2 global static variables a boolean and a string.
For some reason i keep getting segmentation fault from this code . Any idea what could lead to this ? I know this is not thread safe, but i am treating the variables as read only from the java application and only the C++ code is able to modify the values of these variables
Help much appreciated
EDIT : This code runs on a Linux machine . And runs for months at a time without any issues, then it issues a signal 11 segmentation fault and the JVM crashes.
If you're calling the C++ code from multiple threads, and the C++ code has global static variables, then it would be amazing if it worked. The simplest thing to try is to put a lock around the call, i.e. in the Java side change
native int callToCppFunction(int parameter);
to
synchronized native int callToCppFunction(int parameter);
to ensure that only one thread can be in the C++ code at a time.
Then there's another possible issue, which I bumped on about a year ago: apparently in Windows dlls it may not be enough to serialize calls to it (i.e. use synchronized). They may also require to be called from the same thread each time. This answer offers an explanation to how that can be. The solution is to make a single threaded executor to the Java side, and route all calls to the native code through it.

Categories

Resources