Saturday, April 7, 2012

Why Standard Java is not considered appropriate for hard real-time applications

When people hear about real-time computing they often make the mistake of thinking that these have to be fast systems and are nearly always used for control of mechanical systems. It is true that in most cases the response times required are fast, but speed is not what defines a real-time system. The true core of a real-time environment is that the system will guarantee to perform some task within a pre-defined time so that the system's behaviour becomes fully deterministic.

For enterprise class applications what are the advantages (and possibly disadvantages) of deployment on a real-time system? In many cases there is no great advantage. Once the non-functional requirements of a system (load capacity, average response time, peak-load response time, and so on) have been met the application can be deployed and the customer is satisfied. Should something happen that makes a request to, say, an HR application take rather longer than usual the user simply has to wait longer; there is no measurable impact. However, for many financial, enterprise class applications failing to do something within a given time can easily be equated to a cost, possibly a very large one. Financial markets, by their very definition, are extremely volatile and computer trading systems mean that prices can change at the rate of many times a second. If one part of a system decides to make a trade based on the current price and the actual trade gets delayed for whatever reason even a small change can result in a significant loss of money. If this delay happens frequently the system soon becomes less of an advantage and more of a liability.

Java, the language, and the Java Enterprise Edition platform have proved to be very popular for the development of enterprise applications. The ease-of-development, performance and reliability all make Java extremely attractive to developers. However, the Java platform does not support real-time applications, and even running a Java application on a real-time operating system will not make the application deterministic. The biggest obstacle to deterministic behaviour of a Java application is the way memory management is handled by the Java virtual machine (JVM). Unlike earlier languages like C and C++ Java uses a garbage collector to reclaim memory that is no longer being used by an application. The reason for this is to eliminate ‘memory leaks', where a developer forgets to explicitly free memory that is no longer being used. Since the amount of memory in a machine is finite, if this error occurs in some kind of loop eventually the system will run out of memory. (That's not to say you can completely eliminate memory leaks in Java; if a developer maintains references to objects the garbage collector will still not be able to reclaim the memory).

The garbage collector uses a background thread to monitor the heap space where objects are stored. The garbage collector identifies objects that are no longer referenced and reclaim the unused memory. Much of this work involves copying objects from one address to another within the heap. To prevent the possible corruption of data all application threads (referred to as mutator threads) must be paused when this is happening. On modern JVMs these pauses will not be noticeable for well tuned desktop applications. Even for most enterprise applications the use of the concurrent-mark-sweep collector (also known as the low-pause collector) will reduce pauses to levels that are acceptable for most applications. However, for certain classes of enterprise applications like those described earlier, non-deterministic behaviour and therefore Java is not suitable.

To solve this problem a Java Specification Request (JSR) was created to design and implement a real-time specification for Java (RTSJ). This was, in fact, the very first JSR created under the Java Community Process when it was started in 1998. The expert group had several guiding principals in the creation of the specification. Three of these principals are worth noting when considering the applicability to enterprise applications:
  1. Backwards compatibility, so that any class file generated by a Java compliant compiler would run on a RTSJ virtual machine.
  2. No syntactic extensions. No new keywords or syntactic changes would be made to the Java language. This is partly a result of the first point, but is also essential to enable Java developers to easily migrate to RTSJ and use existing development tools such as NetBeans.
  3. Predictable execution. This would be the first priority when making design decisions. The impact of this is that sometimes the typical computing performance may be reduced. This is one reason that an RTSJ system should be considered carefully for general enterprise applications.
The RTSJ specification describes eight areas of extended semantics for Java:
  1. Scheduling
  2. Memory management
  3. Synchronization
  4. Asynchronous event handling
  5. Asynchronous transfer of control
  6. Asynchronous thread termination
  7. Physical memory access
  8. Exceptions
Threads within the RTSJ can be one of three types, non real-time, soft real-time and hard real-time. A non real-time thread is somewhat obvious, in that it does not have a specific deadline when some action must be completed. It can be scheduled when convenient by the JVM and any impact of the garbage collector is immaterial. Soft real-time threads are ones that do have a deadline for completion of an action. However, there is a certain amount of leeway so that if the action gets completed shortly after when it should have done everything will still continue without any problems. For hard real-time threads they absolutely must complete the action by the deadline; if they do not an unrecoverable error has occurred. RTSJ applications can have threads of all three types running simultaneously. The choice of what type of thread to use is down to the designer of the application and the level of importance attached to the work of a thread. The diagram below shows the relationship between these types of threads:



Diagram 1. Threads in the RTJS

Typically threads will need to exchange data for the application to work. Since a hard real-time thread cannot rely on a non real-time thread to deliver results in real-time wait-free data transfer queues are used to ensure that a hard real-time thread is not blocked by other threads.

To create a new non real-time thread the existing Thread class is used unchanged. For soft real-time threads the RealtimeThread class is used, which is a sub-class of Thread. The constructor of this class takes optional priority and release parameters to define how the JVM should schedule the thread. For hard real-time threads the NoHeapRealtimeThread class is used which is a sub-class of RealtimeThread. The name of the class used for hard real-time threads probably gives you a clue about how it is implemented by the JVM; we'll discuss this more when we get to memory management.

The simplest way to convert an existing application to be a real-time application is to simply change all places where a new thread is started to use the RealtimeThread class instead. This would only make the application a soft real-time application, but shows how easy it can be.

The standard Java Thread class includes the concept of a priority so that more important threads can be given preference to lower priority ones. In RTSJ this is extended further and the specification says that there must be at least twenty eight distinct priority levels supported. Since the priority is represented as an integer an implementation could provide many more. The specification also says that threads of a higher priority will always run in preference to those of a lower priority and if a thread with a higher priority becomes runnable it will pre-empt the currently running thread. The classes used to represent this information are shown in diagram 2:

Diagram 2. Thread execution priorities

The PriorityParameters class encapsulates the integer value of the threads priority. If there are multiple threads with the same priority an importance can be associated with the thread to indicate which thread should be given preference.

One of the key concepts of a real-time system is that it should be possible, in advance, to determine whether the system can meet the requirements of the application. In order to do that, through rate monotonic analysis, the system must know details about the tasks. These are provided to the RTSJ through release parameters. The class hierarchy is shown in diagram 3:

Diagram 3. Release parameters

The ReleaseParameters class contains the cost of the thread in terms of time (which is platform specific and may change if the application is moved to a different platform), the deadline for when this task must be completed and handlers for both a cost overrun and a missed deadline. The types of task that will be processed can be either periodic, in which case they happen repeatedly at a given rate, or aperiodic in which case they could happen at any time. If a hard real-time system contains aperiodic tasks it is impossible to analyse for correctness so the concept of a sporadic task is included. This treats an aperiodic task as if it was periodic, giving it a minimum frequency and therefore making it possible to analyse the system. Making an aperiodic task sporadic has no impact to the way the application runs, it just enables the system to determine whether it can meet the real-time requirements.
The RTSJ must also implement what is called priority inversion avoidance. Diagram 4 illustrates the problem:

Diagram 4. Priority inversion

A low priority thread (at priority P3) acquires the lock on an object and is pre-empted by a higher priority thread (at priority P1), as the specification mandates. The P1 thread then needs the same object but cannot acquire the lock until the P3 thread has released it. Other tasks that are lower priority (P2) prevent the P3 thread from running and releasing the lock. The net effect is that P2 priority threads run in preference to the P1 thread which is not what the specification requires. There are two ways to avoid this. The first is priority inheritance. The system detects that the P3 thread is holding a lock required by the P1 thread and elevates its priority to P1 until the lock is released. This works with no changes to the code by the developer. The second way is priority ceiling emulation. Here the developer must realise that the thread holding the lock needs its priority raised and must put explicit calls in the code to do this. This method is optional in the RTSJ.
For memory management RTSJ uses the concept of a memory area. The class structure for this is shown in diagram 5.

Diagram 5. Real time memory areas

Since garbage collection causes non-deterministic pauses all hard real-time threads must use memory that is not subject to garbage collection. There are two ways to do this: scoped memory and immortal memory.

Scoped memory is memory that has a lifetime defined by the developer of an application. A developer will create a scoped memory area of a specific size and when objects are instantiated the space for them will be allocated from this area. There are two types of scoped memory, linear and variable which refers to the time required to instantiate an object. The LTMemory class represents an area of memory where the time to instantiate an object is the combination of a fixed allocation time and a variable initialisation time. Since the initialisation time is directly proportional to the size of the object the time is linear rather than constant. The VTMemory class represents an area of memory where the allocation mechanism can use any algorithm and hence can vary in time. Once all objects in the scoped memory are no longer referenced the memory is freed to be used again. One scenario for the use of scoped memory is to create a scoped memory area and provide it for use by a NoHeapRealTimeThread. When the thread execution finishes all objects are known to no longer be referenced and the area can be freed.

Immortal memory, as the name suggests, never gets collected in any way. Immortal memory is shared by all threads and should only be used for objects that the developer knows will exist until the JVM terminates.

The RTSJ specification also allows developers to do something that is impossible in standard Java: access physical memory directly. Since this is mostly applicable to embedded real-time applications and not enterprise applications we won't discuss this further in this article.

As you can see the RTSJ provides a range of capabilities to allow an enterprise application to run as a combination of non real-time, soft real-time and hard real-time threads. For financial applications where time is money the critical sections can be coded to run as hard real-time threads and avoid the non-deterministic behaviour of the garbage collector. With the release of RTSJ 2.0 a reference implementation is now available that runs on the freely available, open source Solaris 10 operating environment which has a real-time scheduler. (To provide real-time functionality in the JVM the operating system underneath must also support the concepts of real-time).

The obvious next step for enterprise applications is to use a real-time capable application server. Engineers at Sun have ported the GlassFish open source application server to RTSJ (in only five hours). IBM also has a real-time WebSphere product so progress has already been made. When evaluating the use of real-time Java for your enterprise application remember that, in this situation, nothing is free. You may get guaranteed response time, but this will come at the cost of overall throughput of the system. However, if your Java application really, really must respond within a certain time regardless of what the garbage collector does, RTSJ is now a possibility rather than a probability.

Saturday, March 31, 2012

bash - alias, function and script

In Bash, when to alias, when to script, and when to write a function is as trivial as important it is. Here is a look at the underlying implementation, the "why" behind the "what".

aliases and functions
  • are stored in memory (once they are read).
  • When invoked, they are read from memory and executed by the current shell.
Note that aliases and functions are grouped together for their similarities despite being functionally different.

scripts
  • are stored in files. If the script is located in a $PATH directory, many shells store a hash of its pathname to save time on future $PATH lookups.
  • When invoked, they are read from files (i.e. file I/O takes place), and executed by a subshell (i.e. a fork() will occur), unless sourced directly.
What does this mean? Ideal candidates for functions and aliases are commands that are very frequently used and very short, i.e. the type of things that you want to keep in memory and execute in the current shell for speed (although most OS's will cache commonly used files in memory). Ideal candidates for scripts are very long sequences of commands that are very rarely used, i.e. the type of things you don't want or need to permanently take up memory. A good example is initialization command sequences that only run once. 

This could be important for performance -- function is faster, since it doesn't fork() and exec(). In normal circumstances, the difference is trivial, but if you are debugging a system that is out of memory and is page-thrashing, it could make a big difference.

Also, if you want to modify your current shell environment, you should use a function. For example, a function could change the command lookup $PATH for the current shell, but a script cannot, because it operates on a fork/exec copy of $PATH.

With that said, these considerations probably will not make much of a difference on most modern systems with average memory space and disk speeds. However, if you are ever developing scripts for systems with more extreme requirements (like tiny amounts of RAM or uncommon permanent storage media types), it may be useful to keep them in mind. Also, the difference between scripts and functions might be noticeable if you execute them a very large number of times in a row, like iterating over a long file list or a bunch of lines in very long file. Chances are, the function / alias will run faster because it does not need to fork a process or read a disk file, although again, OS-level caching and other optimizations may reduce the differences somewhat.

PS: According to Bash Reference Manual
"For almost every purpose, shell functions are preferred over aliases."

Thursday, March 8, 2012

OLTP vs. OLAP

We can divide IT systems into transactional (OLTP) and analytical (OLAP). In general we can assume that OLTP systems provide source data to data warehouses, whereas OLAP systems help to analyze it. 

OLTP (On-line Transaction Processing) is characterized by a large number of short on-line transactions (INSERT, UPDATE, DELETE). The main emphasis for OLTP systems is put on very fast query processing, maintaining data integrity in multi-access environments and an effectiveness measured by number of transactions per second. In OLTP database there is detailed and current data, and schema used to store transactional databases is the entity model (usually 3NF).

OLAP (On-line Analytical Processing) is characterized by relatively low volume of transactions. Queries are often very complex and involve aggregations. For OLAP systems a response time is an effectiveness measure. OLAP applications are widely used by Data Mining techniques. In OLAP database there is aggregated, historical data, stored in multi-dimensional schemas (usually star schema).

The following table summarizes the major differences between OLTP and OLAP system design.



OLTP System
Online Transaction Processing
(Operational System)

OLAP System
Online Analytical Processing
(Data Warehouse)

Source of data
Operational data; OLTPs are the original source of the data.
Consolidation data; OLAP data comes from the various OLTP Databases
Purpose of data
To control and run fundamental business tasks
To help with planning, problem solving, and decision support
What the data
Reveals a snapshot of ongoing business processes
Multi-dimensional views of various kinds of business activities
Inserts and Updates
Short and fast inserts and updates initiated by end users
Periodic long-running batch jobs refresh the data
Queries
Relatively standardized and simple queries Returning relatively few records
Often complex queries involving aggregations
Processing Speed
Typically very fast
Depends on the amount of data involved; batch data refreshes and complex queries may take many hours; query speed can be improved by creating indexes
Space Requirements
Can be relatively small if historical data is archived
Larger due to the existence of aggregation structures and history data; requires more indexes than OLTP
Database Design
Highly normalized with many tables
Typically de-normalized with fewer tables; use of star and/or snowflake schemas
Backup and Recovery
Backup religiously; operational data is critical to run the business, data loss is likely to entail significant monetary loss and legal liability
Instead of regular backups, some environments may consider simply reloading the OLTP data as a recovery method



Comparison of Bill Inmon and Ralph Kimball paradigm:

In the data warehousing field, we often hear about discussions on where a person / organization's philosophy falls into Bill Inmon's camp or into Ralph Kimball's camp. We describe below the difference between the two.

Bill Inmon's paradigm: Data warehouse is one part of the overall business intelligence system. An enterprise has one data warehouse, and data marts source their information from the data warehouse. In the data warehouse, information is stored in 3rd normal form.

Bill Inmon: Endorses a Top-Down design
Independent data marts cannot comprise an effective EDW. Organizations must focus on building EDW.
"You can catch all the minnows in the ocean and stack them together and they still do not make a whale,"
Bill Inmon, January 8, 1998.

Ralph Kimball's paradigm: Data warehouse is the conglomerate of all data marts within the enterprise . Information is always stored in the dimensional model.
Kimball model also proposes the data warehouse bus architecture. This architecture is comprised of:
  • A staging area (which can have an E/R or relationally designed 3NF design or flat file format), which cannot be accessed by an end-user of the data warehouse bus (Presentation Layer) .
  • The Data Warehouse Bus itself which includes several atomic data marts, several aggregated data marts and a personal data mart but no single or centralized data warehouse component.
The Data Warehouse Bus:
  • Is dimensional;
  • Contains transaction and summary data;
  • Includes data marts, which have single subject or fact tables; and
  • Can consist of multiple data marts in a single data base.
There is no right or wrong between these two ideas, as they represent different data warehousing philosophies. In reality, the data warehouse in most enterprises are closer to Ralph Kimball's idea. This is because most data warehouses started out as a departmental effort, and hence they originated as a data mart. Only when more data marts are built later do they evolve into a data warehouse.

Ralph Kimball: Endorses a Bottom-Up design
EDW effectively grows up around many of the several independent data marts – such as for sales, inventory, or marketing
"...The data warehouse is nothing more than the union of all the data marts...,"
Ralph Kimball, December 29, 1997.

 
The main difference is Top-Down vs. Bottom-Up Approach.

Advantages of Top-Down Approach: [Bill Inmon Approach]:
  • A truly corporate effort, an enterprise view of data
  • Inherently architect ed- not a union of disparate DataMarts
  • Central rules and control
  • May be developed fast using iterative approach
Disadvantages of Top-Down [Bill Inmon Approach]:
  • Takes longer to build even with iterative method
  • High exposure/risk to failure
  • Needs high level of cross functional skills
  • High outlay without proof of concept
  • Difficult to sell this approach to senior management and sponsors
Advantages of Bottom-Up Approach [Ralph Kimball Approach]:
  • Faster and easier implementation of manageable pieces
  • Favorable ROI and proof of concept
  • Less risk of failure
  • Inherently incremental; can schedule important DataMarts first
  • Allows project team to learn and grow
Disadvantages of Bottom-Up Approach [Ralph Kimball Approach]:
  • Each DataMart has its own narrow view of data
  • Permeates redundant data in every DataMart
  • Difficult to integrate if the overall requirements are not considered in the beginning
Kimball encourages to have perspective of both “vertically” and “horizontally”
while gathering business requirements while developing/designing data marts using Bus Architecture to integrate in to Enterprise Data warehouse.

Vertical
  • Don’t just rely on the business data analyst to determine requirements
  • Inputs from senior managers about their vision, objectives, and challenges are critical
  • Ignoring this vertical span might cause failure in understanding the organization’s direction and likely future trends
Horizontal
  • Look horizontally across the departments before designing the Data Warehouse
  • Critical in establishing the enterprise view i.e Bus Architecture
  • Challenging to do if one particular department if funding the project. [Even one departments funds this project , but all the departments together become the company]
  • Ignoring horizontal span will create isolated, department-centric databases that are inconsistent and can’t be integrated while considering for Enterprise Data Warehouse
  • Complete coverage in a large organization is difficult , but CEO or CTO represents all of the departments. They should have the proper understanding of the full business and recommend what is good for whole company not just one department.
  • One rep. from each dept. interacting with the core development team can be of immense help
  • Creating a Business Decision Making group when there is a difference in the perspective from each department would help in resolve these kind of conflicts.
New Practical approach by Kimball
  • Plan and define requirements at the overall corporate level
  • Create a surrounding architecture for a complete warehouse
  • Conform and standardize the data content
  • Implement the Data Warehouse as a series of Supermarts, one at a time

SUPERMARTS
  • Totally monolithic approach vs. totally stovepipe approach
  • A step-by-step approach for building an Enterprise Data Warehouse from granular data
  • A Supermart s a data mart that has been carefully built with a disciplined architectural framework
  • A Supermart is naturally a complete subset of the Data Warehouse.
  • A Supermart is based on the most granular data that can possible be collected and stored
  • Conformed dimensions and standardized fact definitions

OLTP and Data Warehousing Environments

One major difference between the types of system is that data warehouses are not usually in third normal form (3NF), a type of data normalization common in OLTP environments.
Data warehouses and OLTP systems have very different requirements. Here are some examples of differences between typical data warehouses and OLTP systems:
  • Workload
    • Data warehouses are designed to accommodate ad hoc queries. You might not know the workload of your data warehouse in advance, so a data warehouse should be optimized to perform well for a wide variety of possible query operations.
    • OLTP systems support only predefined operations. Your applications might be specifically tuned or designed to support only these operations.
  • Data modifications
    • A data warehouse is updated on a regular basis by the ETL process (run nightly or weekly) using bulk data modification techniques. The end users of a data warehouse do not directly update the data warehouse.
    • In OLTP systems, end users routinely issue individual data modification statements to the database. The OLTP database is always up to date, and reflects the current state of each business transaction.
  • Schema design
    • Data warehouses often use denormalized or partially denormalized schemas (such as a star schema) to optimize query performance.
    • OLTP systems often use fully normalized schemas to optimize update/insert/delete performance, and to guarantee data consistency.
  • Typical operations
    • A typical data warehouse query scans thousands or millions of rows. For example, "Find the total sales for all customers last month."
    • A typical OLTP operation accesses only a handful of records. For example, "Retrieve the current order for this customer."
  • Historical data
    • Data warehouses usually store many months or years of data. This is to support historical analysis.
    • OLTP systems usually store data from only a few weeks or months. The OLTP system stores only historical data as needed to successfully meet the requirements of the current transaction.