views:

549

answers:

3

How would one synchronize one real-time thread with a normal thread in Java? Take for example a real-time thread that calculates some temperatures and the GUI thread that has to collect those numbers and show them on some controls.

The implementation of the real-time library shouldn't matter as it should follow the specifications.

+3  A: 

You're going to need two things. You want your real-time thread to get priority, and preferably have it driven by a timer so you get (nearly) periodic measurements. Then, you're going to want a resource that can be used to communicate the values. That can either be a simple monitor, with a critical section so the timer thread can write into it, or it could be -- and very probably would be better as -- a FIFO, so that the GUI thread can eat up values whenever it has cycles.

In Java, the GUI (at least in Swing and similar) is already running a separate thread for UI interactions, so you're big issue is to set up your measurement thread. Have a look at Runnables.

Charlie Martin
+2  A: 

To use real-time threads you need Real Time Java on real time operating system. http://java.sun.com/javase/technologies/realtime/index.jsp

However if you have a thread which is latency sensitive, I suggest you;

  • use the concurrency libraries in communications with other threads.
  • minimise any GC activity (esp full GCs)
  • don't run the thread in the same process as a GUI if you can (as it tends grab a lot of resources in ways you have limited control over)
Peter Lawrey
+1  A: 

Since others have brought up RTSJ, I'll comment that synchronization between real-time and non-real-time code has a number of solutions. RTSJ provides wait-free queues for such communication. It is also possible to build upon these or other queues and make use of RTSJ's AsyncEvent and AsyncEventHandler abstractions to manage the communication. This is appropriate for situations where you really, truly have a need for deterministic behavior for the "real-time" thread.

If you can accept best-effort behavior (try really hard to hit your deadlines, but the world doesn't fall apart if you miss) I suggest building carefully on the executor framework provided by the Java concurrency utilities. A careful selection of task boundaries, a suitable queuing policy (here, "suitable" would depend on more detail about your application than you've given), and threadpool policy will get what you need.

andersoj