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
Related
I'm writing a separate thread to monitor an OS process spawned by Java's ProcessBuilder. The process can sometimes get out of control. After a given timeout period, I want to kill the process if it's still running. I can paste my code in if it's helpful (please ask), but the only detail directly relevant to the question is that I'm using Process::waitFor to specify the timeout after which the process will be killed.
The problem is that this code design is relatively inefficient. As even the documentation for Process::waitFor says,
The default implementation of this methods polls the {#code exitValue}
to check if the process has terminated. Concrete implementations of this
class are strongly encouraged to override this method with a more
efficient implementation.
I'm thinking a much more efficient design would be to specify a callback to be executed after the process completes. I could execute my own timeout method that would kill the process if it were still running. But the callback, if run, would cancel the timeout kill method.
Can I implement a callback pattern for a process spawned by ProcessBuilder?
I'm looking at the ProcessBuilder.start(Redirect[] redirects) and wondering if I could just tack the execution of the callback at the end of this method. Problem is that the class is final, so I can't subclass it. I'd have to copy and modify. But I'd also have to duplicate such dependencies as ProcessEnvironment and ProcessImpl, which are not public, as well as being final. Ugh.
Is maybe there some way to extend the abstract class Process to use a callback? That class seems to have/be the only space left by the authors of Java for fixing up the inefficient code they've left.
Or perhaps there's another way to make Process::waitFor more efficient?
I implement a custom POSIX signal handler
Ref : http://blog.httrack.com/blog/2013/08/23/catching-posix-signals-on-android/
Their appears to be a platform limitation with ART.
Is there a work around or any other way to achieve, calling java method from JNI through the signal handler method.
If not then is there an alternative scheme to catch the native crash and propagate to the app ?
First of all - you should be very carefully with what you doing in signal handler. Also there is a list of functions that you can safely invoke from there, look for "Async-signal-safe functions". And surely you shouldn't invoke anything outside of that list or anythyng via JNIEnv because you don't know what JVM does under the hood.
As result there is no way to propagate error to the app. You can just write anything you want to some file with write() and then test this file at next launch.
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.
I'm calling a C function that resides in a dll from a java thread. This C function runs indefinitely and processes video frames in real time, outputting a result for each frame.
I want to spawn another java thread to read the results from the processing function without interrupting the function. I also need to implement some kind of thread control to protect from reading corrupted data.
Any ideas?
The global is controlled by your C environment.
I suspect that you should do this:
Create a function that returns the value of the global variable and call it from java using JNI.
Implement your synchronization stuff in C.
You can embed your C function in a executable that will be started by your java thread. The C function can post results into a pipe or send them through a socket to your java thread. This gives you the flexibility to even have your C function running on one machine and the java thread on another.
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.