RT Java

1,239 views
1,157 views

Published on

Published in: Business, Economy & Finance
0 Comments
0 Likes
Statistics
Notes
  • Be the first to comment

  • Be the first to like this

No Downloads
Views
Total views
1,239
On SlideShare
0
From Embeds
0
Number of Embeds
2
Actions
Shares
0
Downloads
25
Comments
0
Likes
0
Embeds 0
No embeds

No notes for slide

RT Java

  1. 1. Real-Time Java * Programming Christopher D. Gill [email_address] Center for Distributed Object Computing Department of Computer Science Washington University, St. Louis http://www.cs.wustl.edu/~cdgill/RTSJ/COOTS01_M4.ppt COOTS 2001 Tutorial M4 Monday, January 29, 2001 * Java TM is a registered trademark of Sun Microsystems
  2. 2. Tutorial Objectives <ul><li>Provide an overview of real-time programming issues </li></ul><ul><li>Describe a motivating real-time programming example </li></ul><ul><ul><li>An on-line stock market analysis tool </li></ul></ul><ul><ul><ul><li>Exhibits canonical requirements and issues common to other classes of real-time systems </li></ul></ul></ul><ul><li>Show through incremental evolution of the example </li></ul><ul><ul><li>How real-time programming issues can arise in a Java TM (Java) programming environment </li></ul></ul><ul><ul><li>How features of the Real-Time Specification for Java TM (RTSJ) can be applied to resolve these issues </li></ul></ul>Real-Time Java Programming
  3. 3. Example: Stock Market Analysis Tool <ul><li>Performs automated decision aiding for stock trading </li></ul><ul><li>Inputs arrive from real-time data streams </li></ul><ul><li>May run queries against on-line databases </li></ul><ul><li>Sends alerts to human operator and/or other automated systems with specific recommendations ( e.g., sell, buy, limit order, short, call, put) </li></ul><ul><li>Timeliness of outputs is crucial </li></ul><ul><ul><li>A functionally correct output sent too late can be worse than no output at all </li></ul></ul><ul><li>Several application layers compete in real-time for system resources (i.e., CPU, memory) </li></ul>Real-Time Java Programming
  4. 4. Example: Stock Market Analysis Tool <ul><li>Inputs arrive in real-time from data streams </li></ul><ul><ul><li>Real-time (seconds) arrival of data events </li></ul></ul><ul><ul><li>One feed per market </li></ul></ul><ul><li>May run queries on-line tables and databases: differences in latency and latency jitter </li></ul><ul><ul><li>Analyst reports </li></ul></ul><ul><ul><li>Market histories </li></ul></ul><ul><ul><li>Sector P/E tables </li></ul></ul>DataFeed NYSEFeed NasdaqFeed DataStore NasdaqStore ResearchStore NYSEStore Real-Time Java Programming
  5. 5. Example: Stock Market Analysis Tool <ul><li>Sends recommendations as alerts to: </li></ul><ul><ul><li>Human operators </li></ul></ul><ul><ul><li>Automated systems </li></ul></ul><ul><li>Documented quality of information is key </li></ul><ul><ul><li>Decision path, triggers </li></ul></ul><ul><ul><li>Additional info, links </li></ul></ul><ul><li>Timeliness constraints must also be met </li></ul><ul><ul><li>Incremental addition, refinement is useful </li></ul></ul>MarketOrder Option Call Annotation Alert Put Buy Sell * Real-Time Java Programming
  6. 6. Example: Stock Market Analysis Tool <ul><li>Input events pass through an analysis pipeline </li></ul><ul><ul><li>Each analysis filter handles the data and news events in which it is interested, may search databases </li></ul></ul><ul><ul><li>May attach additional information to event and pass it on or consume it, and/or produce alerts </li></ul></ul><ul><ul><li>Composites combine other analysis filters </li></ul></ul>AnalysisPipeline AnalysisFilter SectorPE PortfolioBalance 1 + Composite 1 + Real-Time Java Programming
  7. 7. Example: Roadmap NasdaqAnnotation AnalysisPipeline AlertList SectorPEFilter PortfolioBalanceFilter CompositeFilter MarketOrderAlert OptionAlert CallAlert Alert PutAlert BuyAlert SellAlert AnalysisFilter AnalysisTool Annotation ResearchAnnotation DataStore NasdaqStore ResearchStore AnnotationList Portfolio DataFeed DataFeedEvent NasdaqDataFeed Real-Time Java Programming
  8. 8. Example: Stock Market Analysis Tool <ul><li>// Input Event Streams Code </li></ul><ul><li>public class DataFeedEvent </li></ul><ul><li>{ private float bid; </li></ul><ul><li>private float ask; </li></ul><ul><li>private float change; </li></ul><ul><li>private long volume; </li></ul><ul><li>// ... </li></ul><ul><li>public DataFeedEvent </li></ul><ul><li>(float b, float a, </li></ul><ul><li>float c, long v) </li></ul><ul><li>{bid = b; ask = a; </li></ul><ul><li>change = c; volume = v;} </li></ul><ul><li>public float getBid () {return bid;} </li></ul><ul><li>public float getAsk () {return ask;} </li></ul><ul><li>public float getChange () {return change;} </li></ul><ul><li>public long getVolume () {return volume;} </li></ul><ul><li>// ... </li></ul><ul><li>} </li></ul>Real-Time Java Programming data event 90 seconds data feed Market market order
  9. 9. Example: Stock Market Analysis Tool <ul><li>// Input Event Streams Code, Continued </li></ul><ul><li>public abstract class DataFeed </li></ul><ul><li>{ public abstract DataFeedEvent </li></ul><ul><li>pullDataFeedEvent (); </li></ul><ul><li>} </li></ul><ul><li>public class NasdaqDataFeed extends DataFeed </li></ul><ul><li>{ // low-ish latency </li></ul><ul><li>public DataFeedEvent pullDataFeedEvent () </li></ul><ul><li>{ return pullNasdaqDataFeedEvent (); </li></ul><ul><li>} </li></ul><ul><li>protected DataFeedEvent pullNasdaqDataFeedEvent () </li></ul><ul><li>{ float bid = 0.0F; float ask = 0.0F; </li></ul><ul><li>float chg = 0.0F; long vol = 0; </li></ul><ul><li>// read data from socket, etc... </li></ul><ul><li>return new DataFeedEvent (bid, ask, chg, vol); </li></ul><ul><li>} </li></ul><ul><li>} /* ... Other DataFeed Classes ... */ </li></ul>Real-Time Java Programming <ul><li>Separate data feed for each market </li></ul><ul><li>Low latency to pull an event from a market data feed </li></ul>
  10. 10. Example: Roadmap AnalysisPipeline AlertList SectorPEFilter PortfolioBalanceFilter CompositeFilter AnalysisFilter AnalysisTool DataStore NasdaqStore ResearchStore Portfolio DataFeed DataFeedEvent NasdaqDataFeed NasdaqAnnotation MarketOrderAlert OptionAlert CallAlert Alert PutAlert BuyAlert SellAlert Annotation ResearchAnnotation AnnotationList Real-Time Java Programming
  11. 11. Example: Stock Market Analysis Tool <ul><li>// Alerts Code </li></ul><ul><li>public abstract class Annotation { /* ... */ } </li></ul><ul><li>public class AnnotationList </li></ul><ul><li>{ private java.util.Vector alist; // list of annotations </li></ul><ul><li>public void addSorted (Annotation a) { /* ... */ } </li></ul><ul><li>} </li></ul><ul><li>public abstract class Alert </li></ul><ul><li>{ private AnnotationList anotes; </li></ul><ul><li>private DataFeedEvent trigger; </li></ul><ul><li>Alert (DataFeedEvent dfe) </li></ul><ul><li>{anotes = new AnnotationList (); </li></ul><ul><li>trigger = dfe;} </li></ul><ul><li>public DataFeedEvent getTrigger () </li></ul><ul><li>{return trigger;} </li></ul><ul><li>public void addAnnotation (Annotation a) </li></ul><ul><li>{ anotes.addSorted (a); } </li></ul><ul><li>public Annotation nextAnnotation (boolean restart) </li></ul><ul><li>{ /* move to next annotation in list, return it ... */ } </li></ul><ul><li>} </li></ul>Real-Time Java Programming trigger Alert annotations
  12. 12. Example: Stock Market Analysis Tool <ul><li>// Alerts Code, Continued </li></ul><ul><li>public abstract class MarketOrderAlert extends Alert </li></ul><ul><li>{ private float orderPrice; private String symbol; </li></ul><ul><li>public MarketOrderAlert (DataFeedEvent dfe, </li></ul><ul><li>float op, String s) </li></ul><ul><li>{super (dfe); orderPrice = op; symbol = s;} </li></ul><ul><li>protected String getSymbol () {return symbol;} </li></ul><ul><li>protected float getOrderPrice () {return orderPrice;} </li></ul><ul><li>} /* ... Similarly, for OptionAlert and its derived classes ... */ </li></ul><ul><li>public class BuyAlert extends MarketOrderAlert </li></ul><ul><li>{ </li></ul><ul><li>public BuyAlert (DataFeedEvent dfe, float op, </li></ul><ul><li>String s) {super (dfe, op, s);} </li></ul><ul><li>float getBuyPrice () { return super.getOrderPrice (); } </li></ul><ul><li>} /* ... Similarly for SellAlert, Other Alert Classes ... */ </li></ul>Real-Time Java Programming
  13. 13. Example: Stock Market Analysis Tool <ul><li>// Data Store Query Code </li></ul><ul><li>public class NasdaqAnnotation extends Annotation </li></ul><ul><li>{ private float sectorAvgEarnings; </li></ul><ul><li>private float sectorPERatio; </li></ul><ul><li>public NasdaqAnnotation (float e, float r) </li></ul><ul><li>{sectorAvgEarnings = e; sectorPERatio = r;} </li></ul><ul><li>public float getSectorAvgEarnings () </li></ul><ul><li>{return sectorAvgEarnings;} </li></ul><ul><li>public float getSectorPERatio () </li></ul><ul><li>{return sectorPERatio;} </li></ul><ul><li>}/* ... Other Annotation Classes */ </li></ul><ul><li>public class ResearchAnnotation </li></ul><ul><li>extends Annotation </li></ul><ul><li>{ // URLs for research reports </li></ul><ul><li>private java.util.Vector research_reports; </li></ul><ul><li>public void addReport (java.net.URL u) {reports.add (u);} </li></ul><ul><li>public java.net.URL nextReport (boolean restart) { /* ... */ } </li></ul><ul><li>}/* ... Other Annotation Classes */ </li></ul>Real-Time Java Programming annotations research reports URL sector analysis table P/E
  14. 14. Example: Roadmap AnalysisPipeline AlertList SectorPEFilter PortfolioBalanceFilter CompositeFilter AnalysisFilter AnalysisTool Portfolio DataFeed DataFeedEvent NasdaqDataFeed NasdaqAnnotation MarketOrderAlert OptionAlert CallAlert Alert PutAlert BuyAlert SellAlert Annotation ResearchAnnotation AnnotationList DataStore NasdaqStore ResearchStore Real-Time Java Programming
  15. 15. Example: Stock Market Analysis Tool <ul><li>// Data Store Query Code, Continued </li></ul><ul><li>public abstract class DataStore </li></ul><ul><li>{ public abstract void </li></ul><ul><li>annotateAlert (Alert a);} </li></ul><ul><li>public class NasdaqStore </li></ul><ul><li>extends DataStore </li></ul><ul><li>{ public float getPE </li></ul><ul><li>(String symbol, boolean sector) </li></ul><ul><li>{/* medium duration */} </li></ul><ul><li>public float getEarnings </li></ul><ul><li>(String symbol) {/*...*/} </li></ul><ul><li>public void annotateAlert (Alert a) </li></ul><ul><li>{ addNasdaqAnnotation (a); /* ... */ } </li></ul><ul><li>protected void addNasdaqAnnotation (Alert a) </li></ul><ul><li>{ float e = 0.0F; float r = 0.0F; </li></ul><ul><li>// compute PE and Earnings averages for the sector </li></ul><ul><li>a.addAnnotation (new NasdaqAnnotation (e, r)); </li></ul><ul><li>} </li></ul><ul><li>} </li></ul>Real-Time Java Programming annotations sector analysis table P/E Nasdaq market history database analysis query
  16. 16. Example: Stock Market Analysis Tool <ul><li>// Data Store Query Code, Continued </li></ul><ul><li>public class ResearchStore extends DataStore </li></ul><ul><li>{ public void annotateAlert (Alert a) </li></ul><ul><li>{ addResearchAnnotation (a);} </li></ul><ul><li>protected void </li></ul><ul><li>addResearchAnnotation (Alert a) </li></ul><ul><li>{ // long duration: guided </li></ul><ul><li>// search for research </li></ul><ul><li>// reports, adding URLS </li></ul><ul><li>// for relevant analyst </li></ul><ul><li>// research reports to </li></ul><ul><li>// the annotation </li></ul><ul><li>// (ordered by relevance </li></ul><ul><li>// & confidence factors) </li></ul><ul><li>// add annotation to alert </li></ul><ul><li>a.addAnnotation </li></ul><ul><li>(new ResearchAnnotation ()); </li></ul><ul><li>} </li></ul><ul><li>} /* ... Other DataStore Classes ... */ </li></ul>Real-Time Java Programming annotations hyper-linked research reports URL report index search agent
  17. 17. Example: Roadmap DataFeed DataFeedEvent NasdaqDataFeed NasdaqAnnotation MarketOrderAlert OptionAlert CallAlert Alert PutAlert BuyAlert SellAlert Annotation ResearchAnnotation AnnotationList DataStore NasdaqStore ResearchStore AnalysisPipeline AlertList SectorPEFilter PortfolioBalanceFilter CompositeFilter AnalysisFilter AnalysisTool Portfolio Real-Time Java Programming
  18. 18. Example: Stock Market Analysis Tool // Analysis Filter Code public class AlertList {// Alerts raised so far private java.util.Vector alerts; public void addAlert (Alert a) {alerts.add (a);} public Alert nextReport (boolean restart) { /* ... */ } public void reset () { alerts.clear ();} } public abstract class AnalysisFilter {public abstract boolean handleDataEvent (DataFeedEvent d, AlertList a); // ... } Real-Time Java Programming data event data feed Analysis filter alert list
  19. 19. Example: Stock Market Analysis Tool // Analysis Filter Code, Continued public class CompositeFilter extends AnalysisFilter { // the composed filters private java.util.Vector filters; public void addFilter (AnalysisFilter af) { filters.add (af); } public boolean handleDataEvent (DataFeedEvent dfe, AlertList al) { boolean consumed = false; for (int i = 0; !consumed && i < filters.size (); ++i) { consumed = ((AnalysisFilter) filters.get(i)).handleDataEvent (dfe, al); } return consumed; } } Real-Time Java Programming data event Composite Filter
  20. 20. Example: Stock Market Analysis Tool // Analysis Filter Code, Continued public class SectorPEFilter extends AnalysisFilter { private NasdaqStore nh; private ResearchStore rr; public boolean handleDataEvent (DataFeedEvent dfe, AlertList al) { boolean consumed = false; // See if event is of interest, // compare its PE to the avg for // its sector, look at existing // alerts, possibly generate // new ones annotated with // relevant research reports rr.annotateAlert (alert) return consumed; } } Real-Time Java Programming research reports sector analysis table Sector P/E Filter data event
  21. 21. Example: Stock Market Analysis Tool // Analysis Filter Code, Continued public class Portfolio { public float projectRiskDelta (DataFeedEvent d) {/*...*/} public float projectGainDelta (DataFeedEvent d) {/*...*/} } public class PortfolioBalanceFilter extends AnalysisFilter { protected Portfolio p; public boolean handleDataEvent (DataFeedEvent dfe, AlertList al) { boolean consumed = false; // issue/remove alerts based on // data feed event and projected // risk/gain to portfolio goals return consumed; } } Real-Time Java Programming Portfolio Balance Filter alert list goals risk profile data event
  22. 22. Example: Stock Market Analysis Tool // Analysis Pipeline Code public class AnalysisPipeline { private CompositeFilter cf; private DataFeed df; private AlertList al; public void addFilter (AnalysisFilter af) {cf.addFilter (af);} public void sendAlerts () {/* Send all alerts, reset list */} public void run () { for (;;) { DataFeedEvent dfe = df.pullDataFeedEvent (); cf.handleDataEvent (dfe, al); // possibly long latency sendAlerts (); /* latency depends on alert count */} } } Real-Time Java Programming data event Filter Pipeline alert list send alerts Operator
  23. 23. Example: Stock Market Analysis Tool <ul><li>// Analysis Tool Code </li></ul><ul><li>public class AnalysisTool </li></ul><ul><li>{ </li></ul><ul><li>public static void main </li></ul><ul><li>(String [] args) </li></ul><ul><li>{ AnalysisPipeline ap = </li></ul><ul><li>new AnalysisPipeline (); </li></ul><ul><li>ap.addFilter </li></ul><ul><li>(new PortfolioBalanceFilter ()); </li></ul><ul><li>ap.addFilter </li></ul><ul><li>(new SectorPEFilter ()); </li></ul><ul><li>ap.run (); // run the pipeline </li></ul><ul><li>} </li></ul><ul><li>} </li></ul>Real-Time Java Programming data event data feed Market market order alert list send alerts
  24. 24. Review: Roadmap AnalysisPipeline AlertList SectorPEFilter PortfolioBalanceFilter CompositeFilter MarketOrderAlert OptionAlert CallAlert DataFeed Alert PutAlert BuyAlert SellAlert AnalysisFilter AnalysisTool Annotation DataFeedEvent NasdaqDataFeed NasdaqAnnotation ResearchAnnotation DataStore NasdaqStore ResearchStore AnnotationList Portfolio Real-Time Java Programming
  25. 25. Example: Time Scales AlertList MarketOrderAlert OptionAlert CallAlert Alert PutAlert BuyAlert SellAlert AnalysisTool DataFeedEvent ResearchAnnotation ResearchStore AnnotationList Portfolio AnalysisPipeline SectorPEFilter PortfolioBalanceFilter CompositeFilter DataFeed AnalysisFilter NasdaqDataFeed NasdaqAnnotation DataStore NasdaqStore Annotation Real-Time Java Programming Low Medium Latency: High AnalysisTool ResearchAnnotation ResearchStore
  26. 26. Java Real-Time Issues <ul><li>Existing Java TM facilities take us several important steps in the direction of real-time application behavior </li></ul><ul><li>Threads </li></ul><ul><ul><li>Liveness (what and how much happens) </li></ul></ul><ul><ul><li>Threads are used to decouple activity time scales </li></ul></ul><ul><li>Synchronization </li></ul><ul><ul><li>Safety (nothing “unsafe” happens) </li></ul></ul><ul><ul><li>Careful application of monitors can preserve liveness </li></ul></ul><ul><li>We’ll start in a bottom-up liveness-first design mode, using thread adapters (Lea, “Concurrent Programming in Java TM ”) </li></ul>Real-Time Java Programming
  27. 27. <ul><li>Separate threads of execution are useful to improve liveness by doing the following concurrently: </li></ul><ul><ul><li>Getting and handling market data events </li></ul></ul><ul><ul><ul><li>Medium latency </li></ul></ul></ul><ul><ul><li>Searching stores to add annotations </li></ul></ul><ul><ul><ul><li>High latency </li></ul></ul></ul><ul><ul><li>Issuing alerts </li></ul></ul><ul><ul><ul><li>Low latency </li></ul></ul></ul>Java: Threading Issues // Analysis Tool Code, Revisited // Separate high latency activity public class StoreThreadAdapter implements Runnable { private DataStore store; private Alert alert; public StoreThreadAdapter (DataStore ds, Alert a) { store = ds; alert = a;} public void run () { store.annotateAlert (alert); } } Real-Time Java Programming
  28. 28. Java: Threading Issues // Analysis Filter Code, Revisited public class SectorPEFilter extends AnalysisFilter { private NasdaqStore nh; private ResearchStore rr; public boolean handleDataEvent (DataFeedEvent dfe, AlertList al) { boolean consumed = false; // possibly generate new alerts ... // ... annotated with relevant research reports... Thread annotationThread = new Thread (new StoreThreadAdapter (rr, alert)); annotationThread.setPriority (Thread.MIN_PRIORITY); annotationThread.start (); return consumed; } } Real-Time Java Programming
  29. 29. Java: Threading Issues <ul><li>// Analysis Tool Code, Revisited </li></ul><ul><li>// Separate low latency activity </li></ul><ul><li>public class AlertThreadAdapter implements Runnable </li></ul><ul><li>{ private AnalysisPipeline pipeline; </li></ul><ul><li>private long timeout; </li></ul><ul><li>public AlertThreadAdapter (AnalysisPipeline ap, long t) </li></ul><ul><li>{ pipeline = ap; timeout = t;} </li></ul><ul><li>public void run () </li></ul><ul><li>{ for (;;) // in reality, could use more sophisticated </li></ul><ul><li>{ // loop control e.g., wait, notifyAll, etc. </li></ul><ul><li>try { Thread.sleep (timeout); pipeline.sendAlerts (); } </li></ul><ul><li>catch (java.lang.InterruptedException e) {/* ... */} </li></ul><ul><li>} </li></ul><ul><li>} </li></ul><ul><li>} </li></ul>Real-Time Java Programming
  30. 30. Java: Threading Issues // Analysis Pipeline Code, Revisited // Separate medium latency activity public class AnalysisPipeline { private CompositeFilter cf; // filters in the pipeline private DataFeed df; // paced data event feed private AlertList al; // list of alerts public void addFilter (AnalysisFilter af) {cf.addFilter (af);} public void sendAlerts () {/* Send all alerts in the list, reset alert list */} public void run () { for (;;) { DataFeedEvent dfe = df.pullDataFeedEvent (); cf.handleDataEvent (dfe, al); // possibly long latency } } } Real-Time Java Programming
  31. 31. Java: Threading Issues <ul><li>// Analysis Tool Code, Revisited </li></ul><ul><li>public class AnalysisTool </li></ul><ul><li>{ </li></ul><ul><li>public static void main (String [] args) </li></ul><ul><li>{ AnalysisPipeline ap = new AnalysisPipeline (); </li></ul><ul><li>ap.addFilter (new PortfolioBalanceFilter ()); </li></ul><ul><li>ap.addFilter (new SectorPEFilter ()); </li></ul><ul><li>Thread alertThread = </li></ul><ul><li>new Thread (new AlertThreadAdapter (ap, 1000)); </li></ul><ul><li>alertThread.setPriority (Thread.MAX_PRIORITY); </li></ul><ul><li>alertThread.start (); </li></ul><ul><li>ap.run (); // run pipeline in the current thread </li></ul><ul><li>} </li></ul><ul><li>} </li></ul>Real-Time Java Programming
  32. 32. Java: Synchronization Issues <ul><li>But, before we go further addressing liveness issues, need to address concurrency safety </li></ul><ul><li>Shift to top-down safety-first design mode, using fine-grain synchronization (Lea, “Concurrent Programming in Java TM ”) </li></ul><ul><li>We’ll combine two styles: block and method synchronization </li></ul>// Concurrency safety additions // using method synchronization public abstract class Alert { /* ... */ public synchronized void addAnnotation (Annotation a) {/* ...*/} public synchronized Annotation nextAnnotation (boolean restart) {/*...*/} } Real-Time Java Programming
  33. 33. Java: Synchronization Issues <ul><li>// Concurrency safety additions using block synchronization </li></ul><ul><li>public class AnalysisPipeline </li></ul><ul><li>{ /* ... */ </li></ul><ul><li>protected void sendAlerts () </li></ul><ul><li>{ synchronized (al) </li></ul><ul><li>{/* Send all the alerts in the list, reset alert list */} </li></ul><ul><li>} </li></ul><ul><li>public void run () </li></ul><ul><li>{ for (;;) </li></ul><ul><li>{ DataFeedEvent dfe = df.pullDataFeedEvent (); </li></ul><ul><li>// spawns separate threads for long latency activities </li></ul><ul><li>cf.handleDataEvent (dfe, al); </li></ul><ul><li>} </li></ul><ul><li>} </li></ul>Real-Time Java Programming
  34. 34. Java: Synchronization Issues <ul><li>// Concurrency safety additions using block synchronization </li></ul><ul><li>public class PortfolioBalanceFilter extends AnalysisFilter </li></ul><ul><li>{ protected Portfolio p; </li></ul><ul><li>public boolean handleDataEvent (DataFeedEvent dfe, </li></ul><ul><li>AlertList al) </li></ul><ul><li>{ boolean consumed = false; </li></ul><ul><li>synchronized (al) </li></ul><ul><li>{ /* add alerts based on data feed event and the </li></ul><ul><li>projected risk and gain changes to portfolio */ } </li></ul><ul><li>return consumed; </li></ul><ul><li>} </li></ul><ul><li>} </li></ul>Real-Time Java Programming
  35. 35. Java: Synchronization Issues <ul><li>// Concurrency safety additions using block synchronization </li></ul><ul><li>public class SectorPEFilter extends AnalysisFilter </li></ul><ul><li>{ private NasdaqStore nh; </li></ul><ul><li>private ResearchStore rr; </li></ul><ul><li>public boolean handleDataEvent (DataFeedEvent dfe, </li></ul><ul><li>AlertList al) </li></ul><ul><li>{ boolean consumed = false; </li></ul><ul><li>/* compare PE to the average for its sector */ </li></ul><ul><li>synchronized (al) { /* look at existing alerts*/ } </li></ul><ul><li>/* possibly generate new ones, annotated in a separate </li></ul><ul><li>thread with relevant research reports... */ </li></ul><ul><li>synchronized (al) { /* add any new alerts to the list */ } </li></ul><ul><li>return consumed; </li></ul><ul><li>} </li></ul><ul><li>} </li></ul>Real-Time Java Programming
  36. 36. Threads and Synch Points AnalysisPipeline SectorPEFilter PortfolioBalanceFilter CompositeFilter MarketOrderAlert OptionAlert CallAlert DataFeed Alert PutAlert BuyAlert SellAlert AnalysisFilter AnalysisTool Annotation DataFeedEvent NasdaqDataFeed NasdaqAnnotation ResearchAnnotation DataStore NasdaqStore ResearchStore Portfolio AlertList AnnotationList Real-Time Java Programming low latency high latency medium latency Synchronization points: AlertList AnnotationList
  37. 37. The RTSJ and Real-Time Issues <ul><li>Threads (revisited) </li></ul><ul><li>Release characteristics & failures </li></ul><ul><li>Scheduling </li></ul><ul><li>Synchronization (revisited) </li></ul><ul><li>Time and timers </li></ul><ul><li>Asynchronous event handling </li></ul><ul><li>Memory management </li></ul><ul><li>Asynchronous transfer of control </li></ul><ul><li>Exceptions </li></ul><ul><li>System-level options </li></ul>Real-Time Java Programming
  38. 38. RT Issues: Threads <ul><li>Multi-threading is useful to decouple different activities </li></ul><ul><ul><li>Active objects, request queues, synch/asynch </li></ul></ul><ul><li>Must ensure resource usage by non-critical activities does not interfere with needs of critical activities </li></ul><ul><li>However, work in different threads competes for CPU time and memory resources </li></ul>Real-Time Java Programming
  39. 39. RTSJ: Threading Issues <ul><li>Threads compete for time on the CPU </li></ul><ul><li>Some activities are higher priority than others </li></ul><ul><li>Java thread priorities take us a step in the right direction, but… </li></ul><ul><ul><li>garbage collector thread priority and preemption issues </li></ul></ul><ul><ul><li>Non-RT priority uniqueness is not ensured </li></ul></ul>// Solution: real-time threads AlertThreadAdapter alertAdapter = new AlertThreadAdapter (ap, 1000); javax.realtime.RealtimeThread alertThread = new javax.realtime.RealtimeThread (alertAdapter); javax.realtime.RealtimeThread pipelineThread = new javax.realtime.RealtimeThread (ap); alertThread.start (); pipelineThread.start (); Real-Time Java Programming
  40. 40. RTSJ: Threading Issues <ul><li>// To run the pipeline in a Realtime thread, it could just implement Runnable: for AnalysisPipeline this is not very invasive so we’ll skip writing a separate adapter </li></ul><ul><li>public class AnalysisPipeline </li></ul><ul><li>{ /* ... */ </li></ul><ul><li>protected void sendAlerts () </li></ul><ul><li>{ synchronized (al) </li></ul><ul><li>{/* Send all the alerts in the list, reset alert list */} </li></ul><ul><li>} </li></ul><ul><li>public void run () </li></ul><ul><li>{ for (;;) </li></ul><ul><li>{ DataFeedEvent dfe = df.pullDataFeedEvent (); </li></ul><ul><li>// spawns separate threads for long latency activities </li></ul><ul><li>cf.handleDataEvent (dfe, al); </li></ul><ul><li>} </li></ul><ul><li>} </li></ul>implements Runnable Real-Time Java Programming
  41. 41. RT Issues: Release Characteristics <ul><li>To know whether threads will interfere, need to characterize their temporal behavior </li></ul>Time <ul><li>Can abstract out separate descriptors for canonical behavioral classes </li></ul><ul><ul><li>I.e., periodic, aperiodic, sporadic </li></ul></ul><ul><li>Need descriptors with key temporal attributes </li></ul><ul><ul><li>E.g., execution cost, deadline </li></ul></ul>Real-Time Java Programming execution cost period minimum inter-arrival spacing deadline
  42. 42. RTSJ: Release Characteristics Issues <ul><li>While threading allows priority partitioning, specific information and/or constraints on threads are needed </li></ul><ul><li>Must ensure sufficient resources are available and correctly managed for desired behavior </li></ul>javax.realtime.RelativeTime cost = new javax.realtime.RelativeTime (100, 0); javax.realtime.RelativeTime period = new javax.realtime.RelativeTime (1000, 0); javax.realtime.PeriodicParameters pp = new javax.realtime.PeriodicParameters ( null, // start immediately, period, cost, null, // deadline = period end null, null); alertThread.setReleaseParameters (pp); alertThread.start (); Real-Time Java Programming
  43. 43. RTSJ: Release Characteristics Issues <ul><li>// Analysis Tool Code, Revisited </li></ul><ul><li>public class AlertThreadAdapter implements javax.realtime.Schedulable </li></ul><ul><li>{ /* we can & should get/set release parameters, scheduling </li></ul><ul><li>parameters, memory parameters, ... */ </li></ul><ul><li>public void run () </li></ul><ul><li>{addToFeasibility (); </li></ul><ul><li>javax.realtime.RealtimeThread t = </li></ul><ul><li>(javax.realtime.RealtimeThread) Thread.currentThread (); </li></ul><ul><li>for (;;) </li></ul><ul><li>{ t.waitForNextPeriod (); // respect advertised cost, period times </li></ul><ul><li>pipeline.sendAlerts (); </li></ul><ul><li>} </li></ul><ul><li>} </li></ul><ul><li>} </li></ul>Real-Time Java Programming
  44. 44. <ul><li>Release characteristics advertise how threads are projected to behave </li></ul>RT Issues: Release Failures Time <ul><li>However, differences between projected and actual behavior can lead to unexpected failures </li></ul><ul><li>Need to be able to detect (and if possible handle) release failures </li></ul><ul><ul><li>Cost overruns </li></ul></ul><ul><ul><li>Deadline misses </li></ul></ul>Real-Time Java Programming actual execution cost deadline execution finished (late) projected execution cost
  45. 45. RTSJ: Release Failure Issues <ul><li>Differences between projected and expected behavior result in release failures </li></ul><ul><ul><li>Execution overruns </li></ul></ul><ul><ul><li>Deadline misses </li></ul></ul><ul><li>Can install a handler for each release characteristics instance to at least record, and possibly correct, failures </li></ul>public class CostOverrunEventHandler extends javax.realtime.AsyncEventHandler { public void handleAsyncEvent() {/* ... */}} public class DeadlineMissEventHandler extends javax.realtime.AsyncEventHandler { public void handleAsyncEvent() {/* ... */}} javax.realtime.PeriodicParameters pp = new javax.realtime.PeriodicParameters (null, // start immediately, period, cost, null, // deadline = period end new CostOverrunEventHandler (), new DeadlineMissEventHandler ()); alertThread.setReleaseParameters (pp); alertAdapter.setReleaseParameters (pp); alertThread.start (); Real-Time Java Programming
  46. 46. RT Issues: Scheduling <ul><li>Priorities </li></ul><ul><ul><li>Need sufficient unique priority levels </li></ul></ul><ul><li>Preemptive scheduling </li></ul><ul><ul><li>Need well defined and appropriate semantics </li></ul></ul><ul><li>Fairness among threads is not usually a Real-Time concern (FIFO vs. RR) </li></ul><ul><ul><li>But may be useful </li></ul></ul><ul><li>Feasibility </li></ul><ul><ul><li>Admission control, certification/testing </li></ul></ul>scheduler blocked runnable Real-Time Java Programming executing
  47. 47. RTSJ: Scheduling Issues <ul><li>Release characteristics give control over threads </li></ul><ul><li>Scheduling addresses how to manage those threads </li></ul><ul><li>Priority, preemption </li></ul><ul><li>Feasibility </li></ul>// Analysis Tool Code, Revisited javax.realtime.PriorityScheduler psched = (javax.realtime.PriorityScheduler) javax.realtime.Scheduler.getDefaultScheduler (); javax.realtime.PriorityParameters high = new javax.realtime.PriorityParameters (psched.getMaxPriority ()); javax.realtime.PriorityParameters med = new javax.realtime.PriorityParameters (psched.getNormPriority ()); try { alertThread.setSchedulingParameters (high); pipelineThread. setSchedulingParameters (med); } catch (java.lang.IllegalArgumentException e) {/* ... */} alertThread.start (); pipelineThread.start (); Real-Time Java Programming
  48. 48. RTSJ: Scheduling Issues // Analysis Tool Code, Revisited public class StoreThreadAdapter implements javax.realtime.Schedulable {/* ... */ public void run () { javax.realtime.PriorityScheduler psched = (javax.realtime.PriorityScheduler) javax.realtime.Scheduler.getDefaultScheduler (); try { javax.realtime.PriorityParameters pp = new javax.realtime.PriorityParameters (psched.getMinPriority ()); setSchedulingParameters (pp); javax.realtime.RealtimeThread t = (javax.realtime.RealtimeThread) Thread.currentThread (); t.setSchedulingParameters (pp); } catch (java.lang.IllegalArgumentException e) {/* ... */} store.annotateAlert (alert); } } Real-Time Java Programming
  49. 49. RT Issues: Synchronization <ul><li>Risk of unbounded priority inversions </li></ul><ul><ul><li>Canonical high, low, middle scenario </li></ul></ul>synchronized block waiting (blocked) on a condition variable priority key: high low middle <ul><li>Priorities can uncover or exacerbate “bad” executions of existing race conditions </li></ul><ul><ul><li>Horstmann & Cornell, ”Core Java 2” </li></ul></ul><ul><li>Need well defined thread and locking semantics </li></ul>Real-Time Java Programming blocked at guard running outside block running inside block
  50. 50. RTSJ: Synchronization Issues <ul><li>Real-time threads at different priorities share resources </li></ul><ul><li>However, this presents new real-time issues </li></ul><ul><ul><li>Priority inversions </li></ul></ul><ul><li>Need additional mechanisms to ensure priority-safe sharing </li></ul><ul><ul><li>Monitor Control </li></ul></ul><ul><li>Methods wait and notifyAll still work (avoid notify unless absolutely sure OK) </li></ul><ul><ul><li>But, add overhead </li></ul></ul><ul><li>Non-blocking R/W queues: thread glue </li></ul>// Solution: Monitor Control javax.realtime.MonitorControl.setMonitorControl (new javax.realtime.PriorityInheritance ()); // Solution: wait-free queues public class StoreThreadAdapter implements javax.realtime.Schedulable { /* ... */ private javax.realtime.WaitFreeDequeue dequeue; /* ... */ } Real-Time Java Programming
  51. 51. RT Issues: Time and Timers <ul><li>Time resolution needed </li></ul><ul><ul><li>Hours down to nsec </li></ul></ul><ul><li>Absolute time </li></ul><ul><ul><li>Common temporal reference, e.g., UTC </li></ul></ul><ul><li>Occurrences over time </li></ul><ul><li>Absolute clock </li></ul><ul><li>Timer mechanisms </li></ul><ul><ul><li>One-shot, periodic </li></ul></ul><ul><li>Relative Time </li></ul><ul><ul><li>Since start of thread </li></ul></ul><ul><ul><li>Since last period </li></ul></ul>Real-Time Java Programming start expire
  52. 52. RTSJ: Time and Timer Issues <ul><li>Threads offer a clean programming model </li></ul><ul><li>However, many real-time systems benefit from asynchronous behavior </li></ul><ul><li>Also, pacing is an effective/alternative way to reduce resource contention and improve resource utilization </li></ul>// A needed solution: watchdog timer public class StoreTimeoutHandler extends javax.realtime.AsyncEventHandler {public void handleAsyncEvent() {/* ... */}} public class StoreThreadAdapter implements javax.realtime.Schedulable { public void run () { // ... set up thread priorities ... long m = 60000; // one minute new javax.realtime.OneShotTimer (new javax.realtime.RelativeTime (m,0), new StoreTimeoutHandler ()); store.annotateAlert (alert); } // ... } Real-Time Java Programming
  53. 53. RT Issues: Asynch Event Handling <ul><li>Threads allow synchronous programming styles </li></ul><ul><li>Sometimes, asynchronous styles are more appropriate </li></ul><ul><ul><li>Real-world timing issues </li></ul></ul><ul><ul><li>Decoupling processing </li></ul></ul>handler handler method <ul><li>Events-and-handlers model provides mechanisms for: </li></ul><ul><ul><li>Synchronous –> threads </li></ul></ul><ul><ul><li>Asynchronous –> timers </li></ul></ul><ul><ul><li>Mixed –> half-synch / half-asynch pattern </li></ul></ul>Real-Time Java Programming event
  54. 54. RTSJ: Asynch Event Handling Issues <ul><li>We saw an earlier example of a one-shot timer used to determine when a long-running thread had been gone too long </li></ul><ul><li>Could also use a periodic timer to re-implement the high priority alert transmission code </li></ul>// Another way to implement periodicity public class TransmitTimeoutHandler extends javax.realtime.AsyncEventHandler {public void handleAsyncEvent () {/*...*/}} new javax.realtime.PeriodicTimer (null, new javax.realtime.RelativeTime (1000, 0), new TransmitTimeoutHandler ()); Real-Time Java Programming
  55. 55. RT Issues: Memory Management <ul><li>Bounded allocation times </li></ul><ul><li>Managed vs. raw access </li></ul><ul><ul><li>Trade-off in control vs. responsibility </li></ul></ul><ul><li>Memory lifetimes </li></ul><ul><ul><li>Program, local scope </li></ul></ul><ul><li>Resource use descriptors </li></ul>memory manager <ul><li>Application/manager interactions </li></ul><ul><ul><li>Priority inversions </li></ul></ul><ul><ul><li>Memory contention </li></ul></ul><ul><li>Safety and liveness </li></ul>Real-Time Java Programming
  56. 56. RTSJ: Memory Management Issues <ul><li>Realtime threads get higher priority than the garbage collector </li></ul><ul><li>However, there is still a possibility of priority inversion </li></ul><ul><ul><li>If GC is collecting the heap, it must reach a “safe” state before RT threads can use the heap </li></ul></ul><ul><li>NoHeapRealtime threads avoid this </li></ul>// Solution: separate memory areas and // no-heap real-time threads javax.realtime.MemoryArea ma = new javax.realtime.LTMemory (initSize, maxSize); javax.realtime.NoHeapRealtimeThread alertThread = new javax.realtime.NoHeapRealtimeThread (sp, // sched params rp, // release params mp, // memory params ma, // memory area pg, // processing group alertAdapter); Real-Time Java Programming
  57. 57. RTSJ: Memory Management Issues <ul><li>Scoped memory is key for no-heap real-time threads </li></ul><ul><li>Other kinds of MemoryArea </li></ul><ul><ul><li>Immortal Memory: can improve GC performance </li></ul></ul><ul><li>Physical Memory </li></ul><ul><ul><li>Immortal, scoped, raw </li></ul></ul><ul><ul><li>Factory </li></ul></ul>// Immortal Memory is a Singleton javax.realtime.MemoryArea im = javax.realtime.ImmortalMemory.instance (); im.enter (this); // this must be Runnable // allocates memory on // the ImmortalMemory area // until another memory // area is entered, or // the Runnable run () // call exits and enter () // returns Real-Time Java Programming
  58. 58. RT Issues: Asynch Transfer of Control <ul><li>Want to provide real-time behavior for long-running synchronous activities (e.g., searches) </li></ul><ul><li>For fault-tolerance, some activities may need to be halted immediately </li></ul><ul><li>However, standard threading and interrupt semantics can produce undefined/deadlock behavior in many common use-cases </li></ul><ul><li>ATC refines semantics </li></ul>Publisher Exhaustive Lookup Shipper searching Real-Time Java Programming “ find anything relevant” “ stop and give me what you have found so far”
  59. 59. RTSJ: ATC Issues <ul><li>Even with the one-shot timer, the long running-thread must be reigned in somehow </li></ul><ul><li>Deprecated Thread stop, suspend calls are unsafe </li></ul><ul><li>ATC defers exception as pending in synchronized methods – avoids problem w/deprecated Thread stop method </li></ul>// Data Store Query Code, Revisited public abstract class DataStore { /* ... */ public abstract void annotateAlert (Alert a) throws javax.realtime.AsynchronouslyInterruptedException; } // In timer handling for // StoreThreadAdapter run () t.interrupt (); Real-Time Java Programming
  60. 60. RT Issues: Exceptions <ul><li>Additional special-purpose exceptions w/ standard semantics for </li></ul><ul><ul><li>Memory management </li></ul></ul><ul><ul><li>Synchronization </li></ul></ul><ul><ul><li>System resource management </li></ul></ul><ul><li>Special semantics for ATC </li></ul><ul><ul><li>When to throw (or not) </li></ul></ul><ul><ul><li>Deferred propagation semantics (“exception tunneling”) - safety </li></ul></ul><ul><ul><li>Nesting/replacement </li></ul></ul>Real-Time Java Programming safe scope unsafe scope “ tunnels” propagates caught (re)thrown raised
  61. 61. RTSJ: Exceptions Issues <ul><li>Semantics for AIE are different than others </li></ul><ul><ul><li>deferred in pending state until inside a safe scope, where it will be thrown </li></ul></ul><ul><li>Other new exceptions deal primarily with incompatibilities of memory areas </li></ul><ul><ul><li>Trying to assign a reference to scoped memory to a variable in immortal or heap memory </li></ul></ul><ul><ul><li>Setting up a WaitFreeQueue, exception propagation, etc. in an incompatible memory area </li></ul></ul><ul><ul><li>Raw memory allocation errors (offset, size) </li></ul></ul><ul><ul><li>Raw memory access errors </li></ul></ul>Real-Time Java Programming
  62. 62. RT Issues: System-level Options <ul><li>Although strict layering is often desirable, platform-specific issues tend to peek through </li></ul><ul><ul><li>E.g., signals, schedulers </li></ul></ul><ul><li>Collecting the system-wide constants, methods, etc. under one or more classes reduces pollution and improves the programming model </li></ul><ul><li>May add points of configurability ( I.e., various system-wide managers) </li></ul>SIGKILL SIGINT SIGABRT security manager getManager setManager Real-Time Java Programming
  63. 63. RTSJ: System-level Options Issues <ul><li>javax.realtime.RealtimeSystem is analogous to java.lang.System </li></ul><ul><ul><li>Gives access to real-time system properties </li></ul></ul><ul><ul><ul><li>E.g., concurrent locks, endian properties </li></ul></ul></ul><ul><ul><li>Allows a RealtimeSecurity manager to be set as the system security manager </li></ul></ul><ul><ul><li>Gives access to the current garbage collector </li></ul></ul><ul><li>PosixSignalHandler </li></ul><ul><ul><li>Required on platforms that provide POSIX signals </li></ul></ul><ul><ul><li>Thus, can only be used portably among those implementations </li></ul></ul>Real-Time Java Programming
  64. 64. Review: Time Scales AlertList MarketOrderAlert OptionAlert CallAlert Alert PutAlert BuyAlert SellAlert AnalysisTool DataFeedEvent ResearchAnnotation ResearchStore AnnotationList Portfolio AnalysisPipeline SectorPEFilter PortfolioBalanceFilter CompositeFilter DataFeed AnalysisFilter NasdaqDataFeed NasdaqAnnotation DataStore NasdaqStore Annotation Real-Time Java Programming Low Medium Latency: High AnalysisTool ResearchAnnotation ResearchStore
  65. 65. Review: Java, RTSJ, Real-Time Issues <ul><li>Threads (Java, revisited in RTSJ) </li></ul><ul><li>Release characteristics & failures </li></ul><ul><li>Scheduling </li></ul><ul><li>Synchronization (Java, revisited in RTSJ) </li></ul><ul><li>Time and timers </li></ul><ul><li>Asynchronous event handling </li></ul><ul><li>Memory management </li></ul><ul><li>Asynchronous transfer of control </li></ul><ul><li>Exceptions </li></ul><ul><li>System-level options </li></ul>Real-Time Java Programming
  66. 66. Review: Java and RTSJ AnalysisPipeline SectorPEFilter PortfolioBalanceFilter CompositeFilter MarketOrderAlert OptionAlert CallAlert DataFeed Alert PutAlert BuyAlert SellAlert AnalysisFilter AnalysisTool Annotation DataFeedEvent NasdaqDataFeed NasdaqAnnotation ResearchAnnotation DataStore NasdaqStore ResearchStore Portfolio AlertList AnnotationList real-time periodic no heap feasibile scoped memory priority inheritance high priority over-run handler duration timer aynch transfer of control Real-Time Java Programming low latency high latency medium latency Synchronization points: AlertList AnnotationList
  67. 67. Concluding Remarks <ul><li>The RTSJ extends and/or refines existing Java semantics to address issues of real-time concern </li></ul><ul><ul><li>Priority control, memory management, release parameters, feasibility, … </li></ul></ul><ul><li>However, the RTSJ largely stays within the existing programming model </li></ul><ul><ul><li>Some new idioms to master, but much is preserved </li></ul></ul><ul><ul><li>ATC in particular illustrates the trade-offs </li></ul></ul><ul><li>Stay tuned, more evolution is on the horizon </li></ul><ul><ul><li>Reference implementations and benchmarking </li></ul></ul><ul><ul><li>New specification efforts, e.g., the DRTSJ (JSR 50) </li></ul></ul>Real-Time Java Programming

×