Welcome!

Java Authors: Lori MacVittie, Roger Strukhoff, Esmeralda Swartz, Trevor Parsons, Sandi Mappic

Related Topics: Java

Java: Article

Turbo-Charging Java for Real-Time Applications

Accelerating code execution

The Java platform is usually perceived as inadequate for real-time applications because of its lack of determinism, that is, its unpredictable execution time.

For example, garbage collection (GC), which removes no-longer-needed Java objects and reduces memory overhead, may automatically and transparently freeze the system from time to time. Such behavior is obviously unacceptable in the real-time world. (A commonly recognized goal of real-time computing is to meet an application's time constraints.)

To address this issue, new Java Virtual Machines (JVM) are being developed (e.g., JVM with concurrent GC). In addition, a new Real-Time Specification for Java (RTSJ, JSR-001) has been finalized.

Unfortunately, these solutions achieve predictability to the detriment of performance. For example, concurrent GC is less efficient than "stop the world GC" (which requires total CPU usage), and the memory model advocated by the RTSJ requires runtime checks that impact performance.

This article examines a new solution, one that provides determinism for real-time threads and also has the positive side effect of significantly "accelerating" code execution.

The High Cost of Object Creation
Creating new objects in Java has a significant memory/CPU impact. The impact is somewhat proportional to the object size, but creating even small objects is quite expensive. The memory has to be allocated and initialized and, eventually, when the object is no longer needed, garbage collection is used to free up the memory.

Avoiding memory allocation can significantly increase the performance of your application. (The J.A.D.E. library provides an XML parser significantly faster [2x-3x] than any conventional XML parser only because it does not perform dynamic allocation.)

To minimize object creation and its associated overhead, Java programmers can:

  • Use primitive types: For example, using primitive type "double" is 10 times faster and requires one-third less memory than creating instances of class java.lang.Double.
  • Use the "return value" parameter technique: The basic idea is to avoid object creation by passing a local static object to a function. The function returns this extra parameter after modifying its state to correspond to the desired value. Numerous examples of this technique can be found in the Java standard library (for example, Component.getLocation(Point rv)).
Both of these approaches are error-prone, however. Java primitive types cannot be strongly typed, and the "return value" parameter has to be mutable (modifiable at runtime), which is inherently unsafe (see "Item 13: Favor Immutability," in Effective Java Programming Language Guide by Joshua Bloch for a detailed explanation). Also, the "return value" approach unnecessarily increases the number of Java methods because conventional functions "without" the additional parameter are still provided (for example, Component.getLocation()). To Sun's credit, it should be mentioned that the expense is mitigated quite a bit in their latest versions of Java compared to, say, 1.3.x, especially for short-lived, small objects - thanks to the HotSpot Generational Collector. It may be worthwhile to point this out, even if the improvements don't scale to the same speed as object reuse.

A Real-Time Solution for All Virtual Machines
Garbage collection occurs when memory is being allocated. Therefore, if "new" ready-to-use objects exist (and need not be allocated/initialized because they have been recycled), the memory/CPU is not stressed. As a result, code execution:

  1. Is faster
  2. Is not interrupted by the garbage collector (thereby providing more predictable scheduling)
  3. Has no assignment constraint, as all objects originate from the heap (see RTSJ assignment rules where heap objects cannot refer to scoped objects [JSR-001, pg. 8])
All Java Virtual Machines work in a "heap context" where objects are allocated on demand ("new") and recycled through garbage collection. To support object "recycling" in a transparent manner, we could either use some reference-counting mechanism or work with thread stacks. Due to possible circularities in the general case, the first approach is difficult to implement. The second approach is easier and faster, but the application has to ensure that stack objects are not referenced anymore after the stack is "popped." Fortunately, this risk can be greatly mitigated in practice (using the export method, as we'll see later), which makes this approach far more attractive as a general purpose solution.

Context Programming to the Rescue
Often the same piece of code might have to behave differently based on some thread-locale information. It's not always practical to pass this information as extra parameters to the methods' calls. For example, arithmetic operations might depend on a common modulo number or concurrent threads might log information in separate files. For such situations, the open source J.A.D.E. library defines specific zones called Context, where threads may execute independently from each other (see Java Addition to Default Environment, jade.dautelle.com). The scope of a context is defined by a try-finally block statement, which starts with a static enter call and ends with a static exit call, the class name identifying the type of context; for example:

LocalContext.enter(); // Context used for local setting.
try
   DEBUG.setValue(true);
   ...
} finally {
   LocalContext.exit();
}

Context can be nested; it inherits the setting/behaviors of its outer contexts (unless these setting/behaviors are mutually exclusive). This characteristic also applies to concurrent threads executed while in the context's scope (see Listing 1).

Context programming is somewhat complementary to aspect-oriented programming. Whereas context programming is dynamic by nature (thread based), AOP is typically code based (AspectJ tool/compiler). Both can be used in conjunction to insert custom context code automatically.

The Pool Context
This context implements the "stack" approach mentioned earlier. It ensures that most of the CPU is used to perform the actual task and not maintenance tasks such as memory allocation and garbage collection. In other words the CPU is used at its maximum efficiency.

Pool contexts allow objects to be recycled so that after the pool/stack of recycled objects gets large enough, no memory allocation need ever be performed.

As far as the application is concerned, pool objects need not be mutable; in fact, it's better (safer) if they are immutable. Remember that within a pool context, creating immutable objects is as efficient as reusing mutable objects.

All objects that have been allocated while in a pool context are recycled at the same time when the thread exits the pool context. Recycling is extremely fast and independent from the number of objects allocated (a lot faster than GC). (Recycling is almost instantaneous; it basically consists of resetting the pool/stack's pointers.)

Listing 2 illustrates how pool contexts can be used to accelerate calculations on multiple inputs.

As you can see in Listing 2, it may be necessary to export important results from the current pool context to the outer context to keep these results from being overwritten after the pool objects are recycled. In most cases, the only object that needs to be exported is the result of the operation; all intermediate/temporary objects can be ignored (they are automatically recycled).

No Garbage Collection Ever
For some, a real-time application being interrupted by the garbage collector and consequently missing a deadline is simply not acceptable (considered a critical error in hard real time). Fortunately, by using pool contexts it's relatively easy to avoid running the garbage collector.

There will be no garbage collection ever as long as all your threads run in a pool context, only static constants are exported to the heap, and your system state can be updated without allocating new objects (e.g., StringBuffer instead of string or FastMap instead of HashMap) (see Figure 1). (FastMap class, unlike HashMap, does not allocate a new entry each time a new object is added to the collection.)

For concurrent access/modification of the system state, the use of a reentrant lock is recommended, such as com.dautelle.util.ReentrantLock or the new (JDK1.5) java.util.concurrent.locks.ReentrantLock. Provided that factory methods are used instead of the new keyword for object creations, most of the application code is oblivious of the garbage collection issue. (The new keyword always allocates on the heap. The J.A.D.E. library cannot/does not change the virtual machine behavior with regards to class instantiation.) Particular care should be taken with some JDK library methods that may allocate temporary objects onto the heap at each call (setup/initialization heap allocations are okay), and therefore should be avoided or replaced by cleaner classes (e.g., TypeFormat [J.A.D.E. class: com.dautelle.util.TypeFormat] for parsing/formatting of primitive types). Listing 3 provides an example of a real-time handler processing UDP messages

A Nice Side-Effect: Increase of Execution Speed
The cost of allocating an object on the heap is somewhat proportional to that object's size. The cost of reusing an object, however, is independent of its size. In other words, the larger the object, the more performance gain you can expect from using a pool context. For example, adding 1024-bits immutable integers is up to five times faster (LargeInteger versus BigInteger, J.A.D.E. benchmark results). The high performance associated with pool contexts is due not only to object reuse but also to a more efficient use of the CPU internal cache (cache hits are a lot more frequent when objects are being reused).

Recycling objects is more powerful than just recycling memory (a.k.a. GC). It's particularly true for objects requiring some CPU-intensive setup at initialization (e.g., preallocated linked lists or tables). Unlike hardware recycled objects, software recycled objects are as good as new.

Limitations
The strength of Java resides mostly in its comprehensive library. Unfortunately, the Java API may allocate temporary objects on the heap, which may annihilate the performance gained from using pool contexts (if you save 100 allocations, that's good…but if the API does 1,000 allocations in the process of running your code, saving 100 allocations isn't as big a gain as might be imagined). One solution is for the JVM to support pool contexts, making the new keyword context-sensitive. This change would be backward compatible, as the default context is the heap context. Then the whole Java API would be more deterministic and execute faster.

Concurrent Context: Harnessing Hyper-Threading and Multiprocessors Potential
With the JDK1.5 Tiger release, a significant effort has been accomplished with regard to concurrent programming. Still, the JDK1.5 concurrency packages (java.util.concurrent, java.util.concurrent.atomic, and java.util.concurrent.locks) rely on the dynamic creation of new threads in order to take advantage of concurrent algorithms, which is usually a no-no in the real-time world. Furthermore, it's inefficient for low-level libraries (too much overhead) and synchronization can be tricky.

To address this particular issue, a concurrent context has been created. It allows real-time applications to take advantage of parallel algorithms on multiprocessor cards or even single processors with hyper-threading technology without creating new threads. (HyperThreading doubles the number of executing threads per processor.) This objective is achieved by maintaining a limited number of threads on stand-by. These threads can then be utilized on demand to perform concurrent executions. If all concurrent threads are busy, the current thread executes the concurrent operation itself. Concurrent context is easy to use, provides automatic load-balancing between processors with almost no overhead, and does not require any synchronization code as the parent thread is not allowed (blocks on the exit() call) to exit its concurrent context until all concurrent executions are complete. As soon as a concurrent thread completes its execution, it becomes available again for more, resulting in concurrent threads/processors being busy most of the time. Last but not least, concurrent contexts guarantee the same behavior whether or not the execution is performed by the current thread or a concurrent thread, granted that the concurrent execution's order has no impact on the behavior. In particular, any exception raised by a concurrent thread is propagated to the parent thread and concurrent threads execute in the same context as their parent.

ConcurrentContext.enter();
try {
   ConcurrentContext.execute(runnable1);
   ConcurrentContext.execute(runnable2);
   ...
} finally {
   ConcurrentContext.exit(); // Waits for all concurrent threads
}    // to complete.

Direct Memory Access: Struct and Union
It's not rare for real-time/embedded projects to use Java and C/C++ together. By mixing them, projects get the best of both worlds: the high-performance of C/C++ with the rapid development cycle typically associated with Java.

Until recently data exchange was problematic as the storage layout of Java objects is not determined by the compiler. The layout of objects in memory is deferred to runtime and determined by the interpreter (or just-in-time compiler). This approach allows for dynamic loading and binding, but also makes interfacing with C/C++ code difficult.

This particular issue has been addressed in the form of two public domain classes: Struct and Union. These two classes mimic the C struct and union types. They follow the same alignment rules, support the same features (e.g., bit fields, packing), and make it extremely easy to convert C header files to Java classes (one-to-one mapping).

Using these classes, embedded systems can map Java objects to a physical address to control hardware devices or communicate through shared memory with external apps.

Conclusion
Garbage collection is not the only issue preventing Java from being used for a real-time system. Other issues include thread scheduling, accurate timer, synchronization overhead, lock queuing order, class initialization, and maximum interrupt response latency. Until now it has definitively been a "stopper." Because of it, most real-time systems today are developed in C/C++ despite the existence of Java compilers.

The good news is that whereas before you had to use C/C++ and some real-time OS, now you can use GCJ/J.A.D.E. and the same real-time OS (with JNI/Struct for the interface).

Pool contexts are a substitute for the complicated memory model of the RTSJ. The concept of scoped memory and immortal memory and how to transfer data between these areas leads to a cumbersome programming style. And the runtime checks for this model are a real performance killer. However, to see the full advantage of this approach for real time, you need a real-time kernel. Since the RTSJ (implemented as Reference Implementation or jRate) is the only available Java real time, it would be interesting to see some results on top of it.

References

  • J.A.D.E. Real-Time FAQ: jade.dautelle.com/api/com/dautelle/realtime/package-summary.html#FAQ
  • RTJ API: rtj.org/doc/index.html
  • Ajile RTJ chips: www.ajile.com/downloads/aJ100Datasheet_1.3.pdf
  • JStamp: jrealtime.systronix.com/
  • Restriction of Java for Embedded Real-Time Systems: www.jopdesign.com/doc/rtjava.pdf
  • The Real-Time for Java Expert Group: www.rtj.org
  • Brosgol, B., et al. (2000). The Real-Time Specification for Java. Addison-Wesley.
  • RTSC (JSR-001): www.rtj.org/rtsj-V1.0.pdf
  • Comments (3)

    Share your thoughts on this story.

    Add your comment
    You must be signed in to add a comment. Sign-in | Register

    In accordance with our Comment Policy, we encourage comments that are on topic, relevant and to-the-point. We will remove comments that include profanity, personal attacks, racial slurs, threats of violence, or other inappropriate material that violates our Terms and Conditions, and will block users who make repeated violations. We ask all readers to expect diversity of opinion and to treat one another with dignity and respect.


    @ThingsExpo Stories
    The Internet of Things will greatly expand the opportunities for data collection and new business models driven off of that data. In her session at Internet of @ThingsExpo, Esmeralda Swartz, CMO of MetraTech, will discuss how for this to be effective you not only need to have infrastructure and operational models capable of utilizing this new phenomenon, but increasingly service providers will need to convince a skeptical public to participate. Get ready to show them the money! Speaker Bio: Esmeralda Swartz, CMO of MetraTech, has spent 16 years as a marketing, product management, and busin...
    Samsung VP Jacopo Lenzi, who headed the company's recent SmartThings acquisition under the auspices of Samsung's Open Innovaction Center (OIC), answered a few questions we had about the deal. This interview was in conjunction with our interview with SmartThings CEO Alex Hawkinson. IoT Journal: SmartThings was developed in an open, standards-agnostic platform, and will now be part of Samsung's Open Innovation Center. Can you elaborate on your commitment to keep the platform open? Jacopo Lenzi: Samsung recognizes that true, accelerated innovation cannot be driven from one source, but requires a...
    SYS-CON Events announced today that Red Hat, the world's leading provider of open source solutions, will exhibit at Internet of @ThingsExpo, which will take place on November 4–6, 2014, at the Santa Clara Convention Center in Santa Clara, CA. Red Hat is the world's leading provider of open source software solutions, using a community-powered approach to reliable and high-performing cloud, Linux, middleware, storage and virtualization technologies. Red Hat also offers award-winning support, training, and consulting services. As the connective hub in a global network of enterprises, partners, a...
    P2P RTC will impact the landscape of communications, shifting from traditional telephony style communications models to OTT (Over-The-Top) cloud assisted & PaaS (Platform as a Service) communication services. The P2P shift will impact many areas of our lives, from mobile communication, human interactive web services, RTC and telephony infrastructure, user federation, security and privacy implications, business costs, and scalability. In his session at Internet of @ThingsExpo, Robin Raymond, Chief Architect at Hookflash Inc., will walk through the shifting landscape of traditional telephone a...
    SYS-CON Events announced today that Matrix.org has been named “Silver Sponsor” of Internet of @ThingsExpo, which will take place on November 4–6, 2014, at the Santa Clara Convention Center in Santa Clara, CA. Matrix is an ambitious new open standard for open, distributed, real-time communication over IP. It defines a new approach for interoperable Instant Messaging and VoIP based on pragmatic HTTP APIs and WebRTC, and provides open source reference implementations to showcase and bootstrap the new standard. Our focus is on simplicity, security, and supporting the fullest feature set.
    BSQUARE is a global leader of embedded software solutions. We enable smart connected systems at the device level and beyond that millions use every day and provide actionable data solutions for the growing Internet of Things (IoT) market. We empower our world-class customers with our products, services and solutions to achieve innovation and success. For more information, visit www.bsquare.com.
    How do APIs and IoT relate? The answer is not as simple as merely adding an API on top of a dumb device, but rather about understanding the architectural patterns for implementing an IoT fabric. There are typically two or three trends: Exposing the device to a management framework Exposing that management framework to a business centric logic • Exposing that business layer and data to end users. This last trend is the IoT stack, which involves a new shift in the separation of what stuff happens, where data lives and where the interface lies. For instance, it’s a mix of architectural style...
    SYS-CON Events announced today that SOA Software, an API management leader, will exhibit at SYS-CON's 15th International Cloud Expo®, which will take place on November 4–6, 2014, at the Santa Clara Convention Center in Santa Clara, CA. SOA Software is a leading provider of API Management and SOA Governance products that equip business to deliver APIs and SOA together to drive their company to meet its business strategy quickly and effectively. SOA Software’s technology helps businesses to accelerate their digital channels with APIs, drive partner adoption, monetize their assets, and achieve a...
    From a software development perspective IoT is about programming "things," about connecting them with each other or integrating them with existing applications. In his session at @ThingsExpo, Yakov Fain, co-founder of Farata Systems and SuranceBay, will show you how small IoT-enabled devices from multiple manufacturers can be integrated into the workflow of an enterprise application. This is a practical demo of building a framework and components in HTML/Java/Mobile technologies to serve as a platform that can integrate new devices as they become available on the market.
    SYS-CON Events announced today that Utimaco will exhibit at SYS-CON's 15th International Cloud Expo®, which will take place on November 4–6, 2014, at the Santa Clara Convention Center in Santa Clara, CA. Utimaco is a leading manufacturer of hardware based security solutions that provide the root of trust to keep cryptographic keys safe, secure critical digital infrastructures and protect high value data assets. Only Utimaco delivers a general-purpose hardware security module (HSM) as a customizable platform to easily integrate into existing software solutions, embed business logic and build s...
    Connected devices are changing the way we go about our everyday life, from wearables to driverless cars, to smart grids and entire industries revolutionizing business opportunities through smart objects, capable of two-way communication. But what happens when objects are given an IP-address, and we rely on that connection, sometimes with our lives? How do we secure those vast data infrastructures and safe-keep the privacy of sensitive information? This session will outline how each and every connected device can uphold a core root of trust via a unique cryptographic signature – a “bir...
    Internet of @ThingsExpo Silicon Valley announced on Thursday its first 12 all-star speakers and sessions for its upcoming event, which will take place November 4-6, 2014, at the Santa Clara Convention Center in California. @ThingsExpo, the first and largest IoT event in the world, debuted at the Javits Center in New York City in June 10-12, 2014 with over 6,000 delegates attending the conference. Among the first 12 announced world class speakers, IBM will present two highly popular IoT sessions, which will take place November 4-6, 2014 at the Santa Clara Convention Center in Santa Clara, Calif...
    Almost everyone sees the potential of Internet of Things but how can businesses truly unlock that potential. The key will be in the ability to discover business insight in the midst of an ocean of Big Data generated from billions of embedded devices via Systems of Discover. Businesses will also need to ensure that they can sustain that insight by leveraging the cloud for global reach, scale and elasticity.
    WebRTC defines no default signaling protocol, causing fragmentation between WebRTC silos. SIP and XMPP provide possibilities, but come with considerable complexity and are not designed for use in a web environment. In his session at Internet of @ThingsExpo, Matthew Hodgson, technical co-founder of the Matrix.org, will discuss how Matrix is a new non-profit Open Source Project that defines both a new HTTP-based standard for VoIP & IM signaling and provides reference implementations.

    SUNNYVALE, Calif., Oct. 20, 2014 /PRNewswire/ -- Spansion Inc. (NYSE: CODE), a global leader in embedded systems, today added 96 new products to the Spansion® FM4 Family of flexible microcontrollers (MCUs). Based on the ARM® Cortex®-M4F core, the new MCUs boast a 200 MHz operating frequency and support a diverse set of on-chip peripherals for enhanced human machine interfaces (HMIs) and machine-to-machine (M2M) communications. The rich set of periphera...

    SYS-CON Events announced today that Aria Systems, the recurring revenue expert, has been named "Bronze Sponsor" of SYS-CON's 15th International Cloud Expo®, which will take place on November 4-6, 2014, at the Santa Clara Convention Center in Santa Clara, CA. Aria Systems helps leading businesses connect their customers with the products and services they love. Industry leaders like Pitney Bowes, Experian, AAA NCNU, VMware, HootSuite and many others choose Aria to power their recurring revenue business and deliver exceptional experiences to their customers.
    The Internet of Things (IoT) is going to require a new way of thinking and of developing software for speed, security and innovation. This requires IT leaders to balance business as usual while anticipating for the next market and technology trends. Cloud provides the right IT asset portfolio to help today’s IT leaders manage the old and prepare for the new. Today the cloud conversation is evolving from private and public to hybrid. This session will provide use cases and insights to reinforce the value of the network in helping organizations to maximize their company’s cloud experience.
    The Internet of Things (IoT) is making everything it touches smarter – smart devices, smart cars and smart cities. And lucky us, we’re just beginning to reap the benefits as we work toward a networked society. However, this technology-driven innovation is impacting more than just individuals. The IoT has an environmental impact as well, which brings us to the theme of this month’s #IoTuesday Twitter chat. The ability to remove inefficiencies through connected objects is driving change throughout every sector, including waste management. BigBelly Solar, located just outside of Boston, is trans...
    SYS-CON Events announced today that Matrix.org has been named “Silver Sponsor” of Internet of @ThingsExpo, which will take place on November 4–6, 2014, at the Santa Clara Convention Center in Santa Clara, CA. Matrix is an ambitious new open standard for open, distributed, real-time communication over IP. It defines a new approach for interoperable Instant Messaging and VoIP based on pragmatic HTTP APIs and WebRTC, and provides open source reference implementations to showcase and bootstrap the new standard. Our focus is on simplicity, security, and supporting the fullest feature set.
    Predicted by Gartner to add $1.9 trillion to the global economy by 2020, the Internet of Everything (IoE) is based on the idea that devices, systems and services will connect in simple, transparent ways, enabling seamless interactions among devices across brands and sectors. As this vision unfolds, it is clear that no single company can accomplish the level of interoperability required to support the horizontal aspects of the IoE. The AllSeen Alliance, announced in December 2013, was formed with the goal to advance IoE adoption and innovation in the connected home, healthcare, education, aut...