G53SRP Systems and Real-Time Programming<br />G53SRP Systems and Real-Time Programming(Last Updated:20 Sept 2009) <br />Year 2009-2010<br />Total Credits: 10 <br />Level: Level 3 <br />Target Students: Third year students in the School of Computer Science. <br />Taught Semesters: <br />SemesterAssessmentAutumn Assessed by end of Autumn Semester <br />Prerequisites: <br />MnemTitleG51PRG Programming <br />Corequisites: None. <br />Summary of Content: This course presumes a background in simple single-threaded imperative programming in Java. It reviews the basics of thread-based concurrent programming and concurrency control in Java. It then introduces embedded and real-time programming, and interfacing to hardware devices. By considering in particular the facilities provided by the Real-Time Specification for Java it explores the specific and additional requirements of programming for real-time and embedded systems, including memory management and physical memory access, use of clocks, scheduling, and asynchronous notifications and transfer of control. Module Web Links:<br /> Reading List<br />Method and Frequency of Class: <br />ActivityNumber of sessionsDuration of a sessionLecture 2 per week1 hour Practical 1 per week1 hour <br />Activities may take place every teaching week of the Semester or only in specified weeks. It is usually specified above if an activity only takes place in some weeks of a SemesterFurther Activity Details:Plus 2 practical programming exercises (non-assessed). <br />Method of Assessment: <br />Assessment TypeWeightRequirementsExam 1 100 2 hr written examination <br />Convenor: V.P.Kallimani, <br />Email: email@example.com <br />http://baggins.nottingham.edu.my/~vpkallimani/ <br />Room No : BB59<br />Education Aims: To give an understanding of the ways in which programs may be elaborated compared to the relatively abstract algorithmic programs which are used to introduce procedural programming. To introduce the issues of event-driven programming, real-time programming, multi-threaded programming, programming with interrupts and interfacing directly to system and related hardware devices. to inform this with examples and a number of practical exercises, including use of multi-threading and asynchronous interaction. <br />Learning Outcomes: <br />Knowledge and Understanding: knowledge of concurrent programming and multi-threading facilities (in Java), understanding of scheduling and the determination of process set schedulability, a grasp of the structure and operation of asynchronous event- and interrupt-driven systems, multi-threaded systems and device driver routines <br />Intellectual Skills: the ability to apply mathematical ability and tools to process-set schedulability <br />Professional Skills: the ability to design and construct simple hardware interface routines, multi-threaded applications and real-time applications (RTSJ) Transferable Skills: the ability to utilise mathematics to solve problems, the ability to retrieve and write reports on information gathered from a variety of sources. <br />Offering School: Computer Science <br /> <br />Resources <br />Suggested primary texts<br />NoName of Author(s)Year of PublicationTitle of BookEditionPublisher’s NameISBN1Alan Burns and Andy WellingsMarch 2001Real-Time Systems and Programming LanguagesIIIAddison Wesley Longman0201729881<br />Suggested secondary texts<br />NoName of Author(s)Year of PublicnTitle of BookEdPublisher ISBN1Wellings, Andrew J2004Concurrent and real-time programming in Java / Andrew Wellings, 1st ed. Wiley, 2004. 1Wiley<br />Web Link<br />http://www.nottingham.ac.uk/is/gateway/readinglists/local/displaylist?module=G53SRP<br />http://www.cs.york.ac.uk/rts/RTSBookThirdEdition.html <br />Module-related pages<br />Topics<br />Real time system, reliability, failure, and fault tolerance techniques<br />Concurrent (multi-threaded) programming in Java <br />Concurrency control in Java <br />Real-time threads in RTSJ <br />Scheduling, schedulability and resource sharing <br />Event-driven and asynchronous programming in Java and RTSJ <br />Hardware interfacing in RTSJ <br />(Interrupting threads, and asynchronous transfer of control in RTSJ - not covered) <br />Plan <br />LectureTopics1Introduction2Real time system, reliability, failure, and fault tolerance techniquesJava , exceptions, threads3Concurrency and Reliability Concurrent Programming with Java Threads4Concurrency control and communication Java Concurrency 1: Synchronisation5Java concurrency 2: wait & notify6Java clocks and time7Case Study1 : Mines Drain system8Introduction to Real Time Scheduling9RTSJ Clocks and Time10Real time Threads (part I):11RTSJ Asynchronous Events12RTSJ Deadlines and cost13Feasibility Analysis14Resource sharing15Case Study2 : Chemical Industry16RTSJ Memory Areas and Parameters17Hardware interfacing18Review<br />Course Notes<br />Introduction: intro.ppt / g53srp-intro-6up.pdfSee also Burns & Wellings chapter 1, and Wellings chapter 1. F22 Ariane 5<br />Concurrent Programming with Java Threads: javathreads.ppt / g53srp-javathreads-6up.pdfCode samples: Print10Test.java<br />Java Concurrency 1: Synchronisation: javaconcurrency1.ppt / g53srp-javaconcurrency1-6up.pdfCode samples: MethodNoSyncTest, MethodSyncTest, StaticMethodNoSyncTest, StaticMethodSyncTest, BlockSyncTest, BlockSyncTest2<br />Java concurrency 2: wait & notify: javaconcurrency2.ppt / g53srp-javaconcurrency2-6up.pdfCode Samples: InfiniteBuffer, InfiniteBufferTest, ReaderWriterLock, ReaderWriterLockTest<br />Java clocks and time: clocksandtime.ppt / g53srp-clocksandtime-6up.pdfCode samples: BusyDelay, SleepDelay, ClockGranularity, DriftingClock, HYPERLINK "
SleepAbsoluteDelay, HYPERLINK "
SleepTimeUnitsDelay, TimedWait, TimerClock, DriftingTimerClock<br />Introduction to Real Time Scheduling: realtimescheduling.ppt / g53srp-realtimescheduling-6up.pdf<br />Introduction to the Real Time Specification for Java: rtsjintro.ppt / g53srp-rtsjintro-6up.pdfRTSJ Javadocs (local access only)See Running_RTSJ.html for details of compiling/running RTSJ applications on the CS (Solaris) computers.<br />RTSJ Clocks and Time: rtsjclocksandtime.ppt / g53srp-rtsjclocksandtime-6up.pdfCode samples: RTClock, RTSleep<br />Realtime Threads (part I): realtimethreads.ppt / g53srp-realtimethreads-6up.pdfCode samples: HelloScheduler, HelloRealtimeThread, NRTPriority (/MyTimedTask), RTPriority, HelloPeriodicThread<br />RTSJ Asynchronous Events: asyncevents.ppt / g53srp-asyncevents-6up.pdfCode samples: HelloAsyncEventHandler, HelloAsyncEventHandler2, SlowAsyncEventHandler, AperiodicAsyncEventHandler, SporadicAsyncEventHandler, HelloOneShotTimer, HelloOneShotTimer2, HelloPeriodicTimer, HelloPeriodicTimer2, DisablePeriodicTimer, HelloPOSIXSignalHandler, HelloBoundAsyncEventCorrection/clarification: aperiodic & sporadic event queue includes current firing/release, e.g. any policy except 'save' with queue length 0 results in the handler never being released.Correction/clarification: AsyncEventHandler operations which manipulate fire count are implicitly manipulating the arrival time queue. These operations do not affect the deadline/cost of the current release (i.e. current call to handleAsyncEvent), but any subsequent release (i.e. call to handleAsyncEvent, e.g. due to incrementing fire count) would have its own deadline & cost. The scheduling of the AsyncEventHandler's run() method is an internal detail.Correction/clarification: the notes incorrectly state that each time a PeriodicTimer is start()ed it catches up any missed firings; in fact, if considers the original start time (given to the constructor, or a revised value specified via reschedule), and if it is in the past it fires once immediately and then starts timing from the current time. <br />RTSJ Deadlines and cost: rtsjdeadlineandcost.ppt / g53srp-rtsjdeadlineandcost-6up.pdfCode samples: HelloDeadlineMissHandler, HYPERLINK "
HelloSchedulePeriodic, HelloCostOverrunHandler<br />Feasibility Analysis: feasibility.ppt / g53srp-feasibility-6up.pdf <br />Resource sharing: resourcesharing.ppt / g53srp-resourcesharing-6up.pdf<br />RTSJ Memory Areas and Parameters: memoryareas.ppt / g53srp-memoryareas-6up.pdf<br />Hardware interfacing: hardware.ppt / g53srp-hardware-6up.pdf<br />Exercises<br />Threads<br />Write a class which extends Thread and prints 'Hello World'. Write an application which creates and starts three such threads.<br />Write a Runnable class which executes a busy loop enough times to take a few seconds and then prints a message. Write an application that (a) runs the method twice in succession (b) starts two threads that each run it once. Time the two versions on a multi-core or multi-processor machine. Repeat for four calls/threads <br />What would happen if the threads had 'setDaemon(true)' called on them before they were started?<br />What would happen if one of the threads in (b) has 'setPriority(Thread.MAX_PRIORITY)' called on it before starting it?<br />Find out about Thread Local Data<br />Write a method with the signature 'void PAR(Runnable tasks )' which runs the given tasks in parallel, returning when they have all completed. Try it out with a task such as that in Print10Test. <br />What is the most tasks that it will execute in parallel? Why? <br />Concurrency (1)<br />Write a simple account class to keep track of a current balance and allow operations on it. In another class write a method with the signature void 'transfer(Account from, Account to, int amount)' which transfers the given amount from one account to another. Ensure that the transfer is atomic as far as any other thread is concerned (e.g. a thread which tries to sum the total money in all accounts should never see an increase or decrease in the total). <br />Write a simple Java program which exhibits deadlock. Work out how/why it exhibits all four requirements for deadlock.<br />Could the transfer example exhibit deadlock? Why/why not? If it does then uuder what circumstances? Could it be changed so that it did not? How?<br />Concurrency (2)<br />Write a finite buffer class. Test it using a version of the InfiniteBufferTest in which the producer is very fast, but the consumer takes some period of time to 'handle' each value.<br />Under what circumstances can the ReaderWriterLock give rise to starvation? Modify the ReaderWriterLockTest program to demonstrate this.<br />Modify the ReaderWriterLock so that it avoids starvation in this situation. What (if any) disadvantages does your new version have?<br />Java clocks and time<br />Write an "
which will print a message at (the next) 3:30pm (or whatever time you prefer). Hint: see java.util.Calendar for help for translating times. <br />Using three java.util.TimerTasks write a "
application which prints "
every 250ms, "
every 1000ms and "
every 1000ms, but starting 500ms later than the bass drum. Justify the choice of the specific java.util.Timer schedule method(s) that you have used.<br />Write a variant of the finite buffer class from the Concurrency (2) exercises which is "
, i.e. it should print "
I'm waiting to put"
I'm waiting to get"
(as appropriate) after every one second of waiting. Test it with (a) a slow consumer and a fast producer and (b) a fast consumer and a slow producer.<br />RTSJ clocks and time<br />Write a program which performs an absolute sleep of 100ms duration 100 times, and prints the average delay actually observed.<br />Do the same for a relative sleep of 100ms. Is it the same? Why/why not?<br />RTSJ realtime threads<br />Write a RTSJ application with three realtime threads to implement the "
application (above), with a different thread for the "
. Try changing the priorities of the three threads and see if it affects the print order.<br />RTSJ asynchronous events<br />Write a RTSJ application with an AsyncEvent which is fired by one thread which repeatedly waits for user input and then fires the event. A separate AsyncEventHandler should print "
each time the event fires.<br />Write a version of the above application which considers the user input to be sporadic, with minimum interarrival time 1000ms, arrival time queue length 2, queue overflow behaviour ignore and MIT violation behaviour save. Check what it does if user input is too fast.<br />Change the MIT violation behaviour to ignore. Check what it does when user input is too fast.<br />Write a RTSJ version of the "
application (above) using a PeriodicTimer each for the "
. Try changing the priorities of the three event handlers and see if it affects the print order. <br />Write a RTSJ application which registers a handler for the POSIX signal USR1 which prints "
You cannot kill me so easily"
. Use the UNIX "
command to send the USR1 signal to it.<br />RTSJ deadline and cost<br />Write a RTSJ application with a periodic realtime thread which runs every 3000ms, with a deadline of 200ms. Each time it should print "
hit enter now!"
and wait for user input (e.g. System.in.read()). If the user is too slow (as indicated by missing the deadline) then it should print "
.<br />Resource sharing<br />Write a RTSJ application with three real-time threads which would exhibit priority inversion. Have it print diagnostic output as threads acquire and release the lock on the shared resource and check that priority inheritance is occurring (think carefully about whether you print before/after acquiring/releasing lock).<br />Write a version of the above application which uses PriorityCeilingEmulation for the shared resource. Check that setting the shared monitor's ceiling too low causes a run-time exception. Note: PriorityCeilingEmulation is an optional part of RTSJ and not supported by the Sun RTSJ JVM on archer - this program will throw an UnsupportedOperationException.<br />Try writing an equivalent application in regular Java. Does it appear to exhibit priority inversion? (Note that the non-strict use of priorities in regular Java will confuse the results)<br />Memory areas and parameters<br />Write a realtime threads which has a maximum memory usage of 10000 bytes and a maximum allocation rate of 1000 bytes/second. By adjusting the rate at which it allocates instances of class java.lang.Object check if the usage limit and/or allocation rate are being enforced. How big does a single Java object appear to be? Partial solution: HelloMemoryParameters.java<br />Write a RTSJ application which uses RawMemoryAccess to access (an arbitrary) 1000 bytes of shared memory. Create two periodic realtime threads, one of which repeatedly writes a random byte into the fourth byte of this memory area, and the other which repeatedly reads the byte from this location.<br />Write a RTSJ application which uses the same RawMemoryAccess as the previous exercise and which writes a range of Java integer values into offset 10 and then reads back and prints the bytes in offsets 10-13 inclusive. Check that the bytes are consistent with the platform's byte order as indicated by RealtimeSystem.BYTE_ORDER.<br />Hardware<br />See past questions, listed above.<br />Reference :<br />Chris GreenhalghLast updated: 2009-01-07<br />