Java Hardware Interrupt Handling - java

I would like to know if it is possible to automatically invoke a Java method when a hardware interrupt is raised.

There may be an alternative.
I'm doing something similar: In an application I monitor 4 mice for clicks. Those clicks generate interrupts but I'm happy enough not to deal with them directly from Java.
Under Linux, it turns out there are device files (/dev/input/mouse#) that spew a bunch of characters when something happens with the mouse. I have a Thread for each one with a FileReader blocking on a read. Once characters arrive, the appertaining thread unblocks and I can do whatever processing I like.
So the idea is: If possible, find a way to get a device driver to make the data accessible to you in file/device form, then you can access it from Java using just IO calls from the Java library, with no weird bit-twiddling code and C required in between.

In principle yes, but it will require some C code and JNI to tie that to Java. If you are very lucky perhaps already someone has already built a suitable library for the paltform you are interested in.
Bottom line: if it can be done in C you can hook that to Java.

If you would like to directly respond to an interrupt from Java, then the VM would have to run in kernel space (or on some systems with user space drivers, in a driver context). The JamaicaVM runs in this mode on some RTOSes such as Thread-X or VxWorks as a DKM. The next release of the RTSJ will support writing interrupt service routines in Java.
The RTSJ can be used to run second level interrupt handlers even in user space. This requires a small device driver that either sends a POSIX signal to the VM or provides a character device interface where one thread in the VM blocks on a read of the device. In the first case, an AsyncEventHandler can be assoicated with the POSIX signal. In the second, the tread that blocks on a read of the device can fire an AsyncEvent each time a byte is read from the device. Then any AsyncEventHandler attached to the AsyncEvebt would be released.
If you would like to try this under Linux, you can download the JamaicaVM personal edition: "http://www.aicas.com/jamaica-pe.html". JamaicaVM has a realtime garbage collector and code can be compiled statically to ensure realtime performance. This is a different deployment model than a conventional JVM.

Here is a paper that handles the same topic. And you may have a look at SWT, I think they're dealing with hardware interrupts aswell, although they may rely on the operating systems API.

It's standard on embedded realtime java. go to www.ajile.com, or systrmonx.com and buy an eval board.
Embedded java is not standard on pc's. you can get realtime java on PC hardware, but not the embedded bit.

Take a look at Swig. The Java implementation has Directors that will allow you to call into Java from C/C++.
I've used this technology to handle interrupts calling into C#, and it worked great. Shouldn't be much different calling Java.

Related

How to signal daemon process to change behaviour

I've written a Java application that is launched as a daemon (I daemonize redirecting stderr and stdout and closing stdin though bash). However, occasionally I would like to be able to message this application and inform it to change certain parts of its behavior. I need to be able to message the application from a terminal, so anything that requires a graphical utility is a no-go.
The change in behaviour is fairly simple. I need a toggle for the state of one thread in my application, and a way to gracefully close the application.
What are my options in achieving this? I know I could have a thread in the process that listens on a socket of some sort for messages, but this seems like overkill for the needs I have.
I'm not too familiar with Signals on Linux/Unix, so I'd like to ask if I could simply set up a custom handler for some signals, and have my code execute when the process receives a signal.
Are there any other options that I simply don't know about or haven't thought about?
Signals may be the easiest. You have SIGUSR1 and SIGUSR2 available for application use and you can write a handler for them to manage your toggle. Generally you don't want to do much in a handler so you can set a switch and your main loop (or whatever) needs to check the switch and act accordingly. Similarly the receipt of the signal could be programmed to read a config file that you changed.
Beyond that you can use any available IPC (fifos, sockets, MQs) but you are going to either have thread blocking on them or somehow incorporate them a select statement (or whatever the java equivalent of that is).
You basically need a small client that communicates with your application (server). So the default solution should be to use some IPC mechanism. Putting an IPC mechanism is a one time effort and is worth the trouble because it scales well with the requirements. Using signals for IPC is not recommended. I think sockets is a good way to go.
Personally, I like to use OS signals for this.
Use java.lang.Runtime.addShutdownHook and send a SIGTERM, SIGINT or SIGHUP.
Be aware that some signals are reserved for internal use, check out the docs for the JVM you are using.
The SignalHandler is not part of the supported, public interface, so your mileage may vary.
If you are instantiating a JVM from C code, simply set signal handlers (in C) before the JVM and you will be fine.

How to pause process run using Java's ProcessBuilder.start()?

Alright, so I'm writing this program that essentially batch runs other java programs for me (multiple times, varying parameters, parallel executions, etc).
So far the running part works great. Using ProcessBuilder's .start() method (equivalent to the Runtime.exec() I believe), it creates a separate java process and off it goes.
Problem is I would like to be able to pause/stop these processes once they've been started. With simple threads this is generally easy to do, however the external process doesn't seem to have any inbuilt functionality for waiting/sleeping, at least not from an external point of view.
My question(s) is this: Is there a way to pause a java.lang.Process object? If not, does anyone know of any related exec libraries that do contain this ability? Barring all of that, is extending Process a more viable alternative?
My question(s) is this: Is there a way to pause a java.lang.Process object?
As you've probably discovered, there's no support for this in the standard API. Process for instance provides no suspend() / resume() methods.
If not, does anyone know of any related exec libraries that do contain this ability?
On POSIX compliant operating systems such as GNU/Linux or Mac OS you could use another system call (using Runtime.exec, ProcessBuilder or some natively implemented library) to issue a kill command.
Using the kill command you can send signals such as SIGSTOP (to suspend a process) and SIGCONT (to resume it).
(You will need to get hold of the process id of the external program. There are plenty of questions and answers around that answers this.)
You will need to create a system for sending messages between processes. You might do this by:
Sending signals, depending on OS. (As aioobe notes.)
Having one process occasionally check for presence/absence of a file that another process can create/delete. (If the file is being read/written, you will need to use file locking.)
Have your "main" process listen on a port, and when it launches the children it tells them (via a comamnd-line argument) how to "phone home" as they start up. Both programs alternate between doing work and checking for handling messages.
From what you have described (all Java programs in a complex batch environment) I would suggest #3, TCP/IP communication.
While it certainly involves extra work, it also gives you the flexibility to send commands or information of whatever kind you want between different processes.
A Process represents a separate process running on the machine. Java definitely does not allow you to pause them through java.lang.Process. You can forcibly stop them using Process.destroy(). For pausing, you will need the co-operation of the spawned process.
What sorts of processes are these? Did you write them?

is it possible to monitor folder using java code?

is there anyone know how to monitor a folder using java? or anyone could gave me a point that how could i start this. here's my thought about it.
start a thread to scan the folder changes,which could be create,delete,update files in this folder or something else happen,like last updated.
but in this case, you have to control thread loop. if this thread loop is not controlled well,then it would be a waste of cpu and may cause a fatal problem.
or,is there any framework or some demo code to do this ? hope we could find a better way to do this. thank u very much.
JDK7's java.nio.file package has a WatchService to support file change notification. You can use it to monitor a directory for changes. This uses native facilities where available, otherwise it uses a primitive mechanism such as polling. Here is a post on it.
For now, you can try jpathwatch, which is an implementation of the WatchService interface and uses native OS functions, instead of polling.
Your thought is not bad.
To monitor a folder in java, the usual way is to control it in a separate thread using a loop.
In order to save CPU, you can use a tempo (check every n seconds).
Then, to notify a change from this thread, you can use the "Observer" design pattern.
The pure Java way would be to spun off a thread that polls the directory and tracks changes.
A more efficient way would be to write an OS specific library (You'll probably have to do it in C or C++) that can use OS specific tools to obtain a notification (via a callback into your Java code), and call it via JNI
No it is not. There are some libraries doing the polling for you such as:
http://mindprod.com/jgloss/filemonitor.html that is free and http://www.teamdev.com/jxfilewatcher that is not free
"Ideally, you would like to avoid polling and have instant notification of changes. To do this would require OS-specific JNI code to hook into the native file system. This would also require high privilege."

Are there any Java VMs which can save their state to a file and then reload that state?

Are there any Java VMs which can save their state to a file and then reload that state?
If so, which ones?
Another option, which may or may not be relevant in your case, is to run the JVM (any JVM) inside a virtual machine. Most virtual machines offer the option to store and resume state, so you should be able to restart your PC, fire up the VM when it comes back up and have the Java process pick up from where it was.
I use VMWare Player for testing on IE at work, and this works as noted above when I close and later reopen it. I don't generally do this when apps are doing anything of note in the VM, but as long as they aren't accessing any external resources (e.g. network sockets), I would expect it to work as if the VM was never shut down.
Continuations are probably be what you are looking for:
[...] first class continuations, which are constructs
that give a programming language the
ability to save the execution state at
any point and return to that point at
a later point in the program.
There are at least two continuation libraries for Java: RIFE continuations and javaflow. I know that javaflow at least allows serializing state to disk:
A Continuation can be serialized if
all objects it captured is also
serializable. In other words, all the
local variables (including all this
objects) need to be marked as
Serializable. In this example, you
need to mark the MyRunnable class as
Serializable . A serialized
continuation can be sent over to
another machine or used later. - Javaflow Tutorial
You should serialize relevant domain-specific objects which can be de-serialized by another JVM run-time.
I'm not aware of any tools persisting an entire JVM. The closest I got to doing this was creating a core dump from a running JVM process using gcore, then using jsadebugd, jmap or jstack to debug it.
For instance:
$ jps # get JVM process ID XXX
$ gcore -o core XXX
$ jsadebugd $JAVA_HOME/bin/java core.XXX
UPDATE
I don't think you're going to find a solution that's portable between architectures just yet.
It is worth noting that many objects cannot be serialized as they have state outside the java context.
e.g. Sockets, Threads, Open files, Database connections.
For this reason, it is difficult to to save the state of a useful application in a generic way.
I'm not aware of JVM's that can store state. Depending on your exact needs, you can maybe consider using Terracotta. Terracotta is essentially able to share heap state between JVM's, and store this state to disk.
This can be used to cluster applications, and/or make the heapstate persistent. In effect, you can use it to start the JVM up and pick up where you left off. For more information check out:
http://www.infoq.com/articles/open-terracotta-intro
Hope this helps.
I've worked on an embedded Java project which used this approach to start up quickly.
The JVM was from Wind River, running on top of VxWorks.
Sun has done some research on "orthogonal persistence", which provides "persistence for the full computational model that is definedby the Java Language Specification":
http://research.sun.com/forest/COM.Sun.Labs.Forest.doc.opjspec.abs.html
PJama is a prototype implementation:
http://research.sun.com/forest/opj.main.html
To my knowledge, there is nothing to capture JVM state and restore it, but people are trying to serialize/deserialize the Thread class to achieve something similar. The closest thing to a working implementation I found was brakes, but you may find more when you google for "thread serialization".
I take it you want to be able to resume from where the snapshot was stored, as if nothing thereafter had happened.
I wonder how many framework components and libraries such functionality would break. Suddenly, you are reviving a JVM state from storage; in the meantime, the clock has mysteriously skipped forward by 23 hours, network connections are no longer valid, GUI objects no longer have any underlying O/S handles... I'd say this is nontrivial, and impossible in the general case without modifying the framework extensively.
If you can get away with just storing the state of your in-memory objects, then something like Prevaylor might work for you. It uses a combination of journalling changes to business objects with a serialized snapshot to record the state of your objects, which you can then reload later.
However, it doesn't store the full JVM state (call stack, GC status etc). If you really need that level of detail, then a specialized JVM might be needed.
The answer at this time is no, there are no JVMs that can 'hibernate' like your operating system can or like VMWare et al can.
You could get half-way there, depending on the complexity of your app, by just serializing state out when the program closes and serializing it back in, but that won't do stuff like pause executing some business logic when you close and then continue when you open it again.

Java for Audio Processing is it Practical?

Is Java a suitable alternative to C / C++ for realtime audio processing?
I am considering an app with ~100 (at max) tracks of audio with delay lines (30s # 48khz), filtering (512 point FIR?), and other DSP type operations occurring on each track simultaneously.
The operations would be converted and performed in floating point.
The system would probably be a quad core 3GHz with 4GB RAM, running Ubuntu.
I have seen articles about Java being much faster than it used to be, coming close to C / C++, and now having realtime extensions as well. Is this reality? Does it require hard core coding and tuning to achieve the %50-%100 performance of C some are spec'ing?
I am really looking for a sense if this is possible and a heads up for any gotchas.
For an audio application you often have only very small parts of code where most of the time is spent.
In Java, you can always use the JNI (Java Native interface) and move your computational heavy code into a C-module (or assembly using SSE if you really need the power). So I'd say use Java and get your code working. If it turns out that you don't meet your performance goal use JNI.
90% of the code will most likely be glue code and application stuff anyway. But keep in mind that you loose some of the cross platform features that way. If you can live with that JNI will always leave you the door open for native code performance.
Java is fine for many audio applications. Contrary to some of the other posters, I find Java audio a joy to work with. Compare the API and resources available to you to the horrendous, barely documented mindf*k that is CoreAudio and you'll be a believer. Java audio suffers from some latency issues, though for many apps this is irrelevant, and a lack of codecs. There are also plenty of people who've never bothered to take the time to write good audio playback engines(hint, never close a SourceDataLine, instead write zeros to it), and subsequently blame Java for their problems. From an API point of view, Java audio is very straightforward, very easy to use, and there is lots and lots of guidance over at jsresources.org.
Sure, why not?
The crucial questions (independent of language, this is from queueing theory) are:
what is the maximum throughput you need to handle (you've specified 100 x 48kHz, is that mono or stereo, how many bits equivalent at that frequency?)
can your Java routines keep up with this rate on the average?
what is the maximum permissible latency?
If your program can keep up with the throughput on the average, and you have enough room for latency, then you should be able to use queues for inputs and outputs, and the only parts of the program that are critical for timing are the pieces that put the data into the input queue and take it out of the output queue and send it to a DAC/speaker/whatever.
Delay lines have low computational load, you just need enough memory (+ memory bandwidth)... in fact you should probably just use the input/output queues for it, i.e. start putting data into the input queue immediately, and start taking data out of the output queue 30s later. If it's not there, your program is too slow...).
FIRs are more expensive, that's probably going to be the bottleneck (& what you'd want to optimize) unless you have some other ugly nasty operation in mind.
I think latency will be your major problem - it is quite hard to maintain latency already in C/C++ on modern OSes, and java surely adds to the problem (garbage collector). The general design for "real-time" audio processing is to have your processing threads running at real time scheduling (SCHED_FIFO on linux kernels, equivalent on other OSes), and those threads should never block. This means no system calls, no malloc, no IO of course, etc... Even paging is a problem (getting a page from disk to memory can easily take several ms), so you should lock some pages to be sure they are never swapped out.
You may be able to do those things in Java, but java makes it more complicated, not easier. I would look into a mixed design, where the core would be in C, and the rest (GUI, etc...) would be in java if you want.
One thing I didn't see in your question is whether you need to play out these processed samples or if you're doing something else with them (encoding them into a file, for example). I'd be more worried about the state of Java's sound engine than in how fast the JVM can crunch samples.
I pushed pretty hard on javax.sound.sampled a few years back and came away deeply unimpressed -- it doesn't compare with equivalent frameworks like OpenAL or Mac/iPhone's Core Audio (both of which I've used at a similar level of intensity). javax.sound.sampled requires you to push your samples into an opaque buffer of unknown duration, which makes synchronization nigh impossible. It's also poorly documented (very hard to find examples of streaming indeterminate-length audio over a Line as opposed to the trivial examples of in-memory Clips), has unimplemented methods (DataLine.getLevel()... whose non-implementation isn't even documented), and to top it off, I believe Sun laid off the last JavaSound engineer years ago.
If I had to use a Java engine for sound mixing and output, I'd probably try to use the JOAL bindings to OpenAL as a first choice, since I'd at least know the engine was currently supported and capable of very low-latency. Though I suspect in the long run that Nils is correct and you'll end up using JNI to call the native sound API.
Yes, Java is great for audio applications. You can use Java and access audio layers via Asio and have really low latency (64 samples latency which is next to nothing) on Windows platform. It means you will have lip-sync on video/movie. More latency on Mac as there is no Asio to "shortcut" the combination of OS X and "Java on top", but still OK. Linux also, but I am more ignorant. See soundpimp.com for a practical (and world first) example of Java and Asio working in perfect harmony. Also see the NRK Radio&tv Android app containing a sw mp3 decoder (from Java). You can do most audio things with Java, and then use a native layer if extra time critical.
Check out a library called Jsyn.
http://www.softsynth.com/jsyn/
Why not spend a day and write a simple java application that does minimal processing and validate whether the performance is adaquate.
From http://www.jsresources.org/faq_performance.html#java_slow
Let's collect some ethernal wisdom:
The earth is flat.
and, not to forget: Java is slow.
As several applications prove (see links section), Java is sufficient
to build audio editors, multitrack recording systems and MIDI
processing software. Try it out!

Categories