Saturday, April 7, 2012

The Java: An Overview

Introduction

The Java programming language and environment is designed to solve a number of problems in modern programming practice. Java started as a part of a larger project to develop advanced software for consumer electronics. These devices are small, reliable, portable, distributed, real-time embedded systems. When we started the project we intended to use C++, but encountered a number of problems. Initially these were just compiler technology problems, but as time passed more problems emerged that were best solved by changing the language.

Java

Java: A simple, object-oriented, network-savvy, interpreted, robust, secure, architecture neutral, portable, high-performance, multithreaded, dynamic language.
One way to characterize a system is with a set of buzzwords. We use a standard set of them in describing Java. Here's an explanation of what we mean by those buzzwords and the problems we were trying to solve.
Archimedes Inc. is a fictitious software company that produces software to teach about basic physics. This software is designed to interact with the user, providing not only text and illustrations in the manner of a traditional textbook, but also a set of software lab benches on which experiments can be set up and their behavior simulated. The most basic experiment allows students to put together levers and pulleys and see how they act. The italicized narrative of the trials and tribulations of the Archimedes' designers is used here to provide examples of Java language concepts.

Simple

We wanted to build a system that could be programmed easily without a lot of esoteric training and which leveraged today's standard practice. Most programmers working these days use C, and most programmers doing object-oriented programming use C++. So even though we found that C++ was unsuitable, we designed Java as closely to C++ as possible in order to make the system more comprehensible.
Java omits many rarely used, poorly understood, confusing features of C++ that in our experience bring more grief than benefit. These omitted features primarily consist of operator overloading (although the Java language does have method overloading), multiple inheritance, and extensive automatic coercions.
We added automatic garbage collection, thereby simplifying the task of Java programming but making the system somewhat more complicated. A common source of complexity in many C and C++ applications is storage management: the allocation and freeing of memory. By virtue of having automatic garbage collection (periodic freeing of memory not being referenced) the Java language not only makes the programming task easier, it also dramatically cuts down on bugs.
The folks at Archimedes wanted to spend their time thinking about levers and pulleys, but instead spent a lot of time on mundane programming tasks. Their central expertise was teaching, not programming. One of the most complicated of these programming tasks was figuring out where memory was being wasted across their 20K lines of code.
Another aspect of being simple is being small. One of the goals of Java is to enable the construction of software that can run stand-alone in small machines. The Java interpreter and standard libraries have a small footprint. A small size is important for use in embedded systems and so Java can be easily downloaded over the net.

Object-Oriented

This is, unfortunately, one of the most overused buzzwords in the industry. But object-oriented design is very powerful because it facilitates the clean definition of interfaces and makes it possible to provide reusable "software ICs."
Simply stated, object-oriented design is a technique that focuses design on the data (=objects) and on the interfaces to it. To make an analogy with carpentry, an "object-oriented" carpenter would be mostly concerned with the chair he was building, and secondarily with the tools used to make it; a "non-object-oriented" carpenter would think primarily of his tools. Object-oriented design is also the mechanism for defining how modules "plug and play."
The object-oriented facilities of Java are essentially those of C++, with extensions from Objective C for more dynamic method resolution.
The folks at Archimedes had lots of things in their simulation, among them ropes and elastic bands. In their initial C version of the product, they ended up with a pretty big system because they had to write separate software for describing ropes versus elastic bands. When they rewrote their application in an object-oriented style, they found they could define one basic object that represented the common aspects of ropes and elastic bands, and then ropes and elastic bands were defined as variations (subclasses) of the basic type. When it came time to add chains, it was a snap because they could build on what had been written before, rather than writing a whole new object simulation.

Network-Savvy

Java has an extensive library of routines for coping easily with TCP/IP protocols like HTTP and FTP. This makes creating network connections much easier than in C or C++. Java applications can open and access objects across the net via URLs with the same ease that programmers are used to when accessing a local file system.
The folks at Archimedes initially built their stuff for CD ROM. But they had some ideas for interactive learning games that they wanted to try out for their next product. For example, they wanted to allow students on different computers to cooperate in building a machine to be simulated. But all the networking systems they'd seen were complicated and required esoteric software specialists. So they gave up.

Robust

Java is intended for writing programs that must be reliable in a variety of ways. Java puts a lot of emphasis on early checking for possible problems, later dynamic (runtime) checking, and eliminating situations that are error prone.
One of the advantages of a strongly typed language (like C++) is that it allows extensive compile-time checking so bugs can be found early. Unfortunately, C++ inherits a number of loopholes in compile-time checking from C, which is relatively lax (particularly method/procedure declarations). In Java, we require declarations and do not support C-style implicit declarations.
The linker understands the type system and repeats many of the type checks done by the compiler to guard against version mismatch problems.
The single biggest difference between Java and C/C++ is that Java has a pointer model that eliminates the possibility of overwriting memory and corrupting data. Instead of pointer arithmetic, Java has true arrays. This allows subscript checking to be performed. In addition, it is not possible to turn an arbitrary integer into a pointer by casting.
The folks at Archimedes had their application basically working in C pretty quickly. But their schedule kept slipping because of all the small bugs that kept slipping through. They had lots of trouble with memory corruption, versions out-of-sync and interface mismatches. What they gained because C let them pull strange tricks in their code, they paid for in quality assurance time. They also had to reissue their software after the first release because of all the bugs that slipped through.
While Java doesn't make the QA problem go away, it does make it significantly easier.
Very dynamic languages like Lisp, TCL and Smalltalk are often used for prototyping. One of the reasons for their success at this is that they are very robust: you don't have to worry about freeing or corrupting memory. Java programmers can be relatively fearless about dealing with memory because they don't have to worry about it getting corrupted. Because there are no pointers in Java, programs can't accidentally overwrite the end of a memory buffer. Java programs also cannot gain unauthorized access to memory, which could happen in C or C++.
One reason that dynamic languages are good for prototyping is that they don't require you to pin down decisions too early. Java uses another approach to solve this dilemma; Java forces you to make choices explicitly because it has static typing, which the compiler enforces. Along with these choices comes a lot of assistance: you can write method invocations and if you get something wrong, you are informed about it at compile time. You don't have to worry about method invocation error.

Secure

Java is intended for use in networked/distributed environments. Toward that end, a lot of emphasis has been placed on security. Java enables the construction of virus-free, tamper-free systems. The authentication techniques are based on public-key encryption.
There is a strong interplay between "robust" and "secure." For example, the changes to the semantics of pointers make it impossible for applications to forge access to data structures or to access private data in objects that they do not have access to. This closes the door on most activities of viruses.
Someone wrote an interesting "patch" to the PC version of the Archimedes system. They posted this patch to one of the major bulletin boards. Since it was easily available and added some interesting features to the system, lots of people downloaded it. It hadn't been checked out by the folks at Archimedes, but it seemed to work. Until the next April 1st, when thousands of folks discovered rude pictures popping up in their children's lessons. Needless to say, even though they were in no way responsible for the incident, the folks at Archimedes still had a lot of damage to control.

Architecture Neutral

Java was designed to support applications on networks. In general, networks are composed of a variety of systems with a variety of CPU and operating system architectures. To enable a Java application to execute anywhere on the network, the compiler generates an architecture-neutral object file format--the compiled code is executable on many processors, given the presence of the Java runtime system.
This is useful not only for networks but also for single system software distribution. In the present personal computer market, application writers have to produce versions of their application that are compatible with the IBM PC and with the Apple Macintosh. With the PC market (through Windows/NT) diversifying into many CPU architectures, and Apple moving off the 680x0 toward the PowerPC, production of software that runs on all platforms becomes nearly impossible. With Java, the same version of the application runs on all platforms.
The Java compiler does this by generating bytecode instructions which have nothing to do with a particular computer architecture. Rather, they are designed to be both easy to interpret on any machine and easily translated into native machine code on the fly.
Archimedes is a small company. They started out producing their software for the PC since that was the largest market. After a while, they were a large enough company that they could afford to do a port to the Macintosh, but it was a pretty big effort and didn't really pay off. They couldn't afford to port to the PowerPC Macintosh or MIPS NT machine. They couldn't "catch the new wave" as it was happening, and a competitor jumped in...

Portable

Being architecture neutral is a big chunk of being portable, but there's more to it than that. Unlike C and C++, there are no "implementation dependent" aspects of the specification. The sizes of the primitive data types are specified, as is the behavior of arithmetic on them. For example, "int" always means a signed two's complement 32 bit integer, and "float" always means a 32-bit IEEE 754 floating point number. Making these choices is feasible in this day and age because essentially all interesting CPUs share these characteristics.
The libraries that are a part of the system define portable interfaces. For example, there is an abstract Window class and implementations of it for Unix, Windows NT/95, and the Macintosh.
The Java system itself is quite portable. The compiler is written in Java and the runtime is written in ANSI C with a clean portability boundary. The portability boundary is essentially a POSIX subset.

Interpreted

Java bytecodes are translated on the fly to native machine instructions (interpreted) and not stored anywhere. And since linking is a more incremental and lightweight process, the development process can be much more rapid and exploratory.
As a part of the bytecode stream, more compile-time information is carried over and available at runtime. This is what the linker's type checks are based on. It also makes programs more amenable to debugging.
The programmers at Archimedes spent a lot of time waiting for programs to compile and link. They also spent a lot of time tracking down senseless bugs because some changed source files didn't get compiled (despite using a fancy "make" facility), which caused version mismatches; and they had to track down procedures that were declared inconsistently in various parts of their programs. Another couple of months lost in the schedule.

High Performance

While the performance of interpreted bytecodes is usually more than adequate, there are situations where higher performance is required. The bytecodes can be translated on the fly (at runtime) into machine code for the particular CPU the application is running on. For those accustomed to the normal design of a compiler and dynamic loader, this is somewhat like putting the final machine code generator in the dynamic loader.
The bytecode format was designed with generating machine codes in mind, so the actual process of generating machine code is generally simple. Efficient code is produced: the compiler does automatic register allocation and some optimization when it produces the bytecodes.
In interpreted code we're getting about 300,000 method calls per second on an Sun Microsystems SPARCStation 10. The performance of bytecodes converted to machine code is almost indistinguishable from native C or C++.
When Archimedes was starting up, they did a prototype in Smalltalk. This impressed the investors enough that they got funded, but it didn't really help them produce their product: in order to make their simulations fast enough and the system small enough, it had to be rewritten in C.

Multithreaded

There are many things going on at the same time in the world around us. Multithreading is a way of building applications with multiple threads[1] Unfortunately, writing programs that deal with many things happening at once can be much more difficult than writing in the conventional single-threaded C and C++ style.
Java has a sophisticated set of synchronization primitives that are based on the widely used monitor and condition variable paradigm introduced by C.A.R.Hoare[2]. By integrating these concepts into the language (rather than only in classes) they become much easier to use and are more robust. Much of the style of this integration came from Xerox's Cedar/Mesa system.
Other benefits of multithreading are better interactive responsiveness and real-time behavior. This is limited, however, by the underlying platform: stand-alone Java runtime environments have good real-time behavior. Running on top of other systems like Unix, Windows, the Macintosh, or Windows NT limits the real-time responsiveness to that of the underlying system.
Lots of things were going on at once in their simulations. Ropes were being pulled, wheels were turning, levers were rocking, and input from the user was being tracked. Because they had to write all this in a single threaded form, all the things that happen at the same time, even though they had nothing to do with each other, had to be manually intermixed. Using an "event loop" made things a little cleaner, but it was still a mess. The system became fragile and hard to understand. They were pulling in data from all over the net. But originally they were doing it one chunk at a time. This serialized network communication was very slow. When they converted to a multithreaded style, it was trivial to overlap all of their network communication.

Dynamic

In a number of ways, Java is a more dynamic language than C or C++. It was designed to adapt to an evolving environment.
For example, one major problem with C++ in a production environment is a side-effect of the way that code is implemented. If company A produces a class library (a library of plug and play components) and company B buys it and uses it in their product, then if A changes its library and distributes a new release, B will almost certainly have to recompile and redistribute their own software. In an environment where the end user gets A and B's software independently (say A is an OS vendor and B is an application vendor) problems can result.
For example, if A distributes an upgrade to its libraries, then all of the software from B will break. It is possible to avoid this problem in C++, but it is extraordinarily difficult and it effectively means not using any of the language's OO features directly.
Archimedes built their product using the object-oriented graphics library from 3DPC Inc. 3DPC released a new version of the graphics library which several computer manufacturers bundled with their new machines. Customers of Archimedes that bought these new machines discovered to their dismay that their old software no longer worked. (In real life, backwards compatibility isn't always a high priority in the Unix world. In the PC world, 3DPC would never have released such a library: their ability to change their product and use C++'s object oriented features is severely hindered because they can't expect their customers to recompile.)
By making these interconnections between modules later, Java completely avoids these problems and makes the use of the object-oriented paradigm much more straightforward. Libraries can freely add new methods and instance variables without any effect on their clients.
An interface specifies a set of methods that an object can perform but leaves open how the object should implement those methods. A class implements an interface by implementing all the methods contained in the interface. In contrast, inheritance by subclassing passes both a set of methods and their implementations from superclass to subclass. A Java class can implement multiple interfaces but can only inherit from a single superclass. Interfaces promote flexibility and reusability in code by connecting objects in terms of what they can do rather than how they do it.
Classes have a runtime representation: there is a class named Class, instances of which contain runtime class definitions. If, in a C or C++ program, you have a pointer to an object but you don't know what type of object it is, there is no way to find out. However, in Java, finding out based on the runtime type information is straightforward. Because casts are checked at both compile-time and runtime, you can trust a cast in Java. On the other hand, in C and C++, the compiler just trusts that you're doing the right thing.
It is also possible to look up the definition of a class given a string containing its name. This means that you can compute a data type name and have it easily dynamically-linked into the running system.
To expand their revenue stream, the folks at Archimedes wanted to architect their product so that new aftermarket plug-in modules could be added to extend the system. This was possible on the PC, but just barely. They had to hire a couple of new programmers because it was so complicated. This also added problems when debugging.

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.