Java IoT Authors: Elizabeth White, Yeshim Deniz, Zakia Bouachraoui, Liz McMillan, William Schmarzo

Related Topics: Java IoT

Java IoT: Article

Dynamic Code Generation

Dynamic Code Generation

Java is often criticized for its performance, particularly in comparison to equivalent code written in languages such as C and C++. Advances in runtime performance have silenced many critics, but still there are times when no matter how fast Java is, it's just not fast enough.

Fortunately, Java does have some unique properties that make a class of optimizations accessible that are not easily applied to other platforms. One technique that can be used to great effect on certain types of tasks is dynamic code generation.

Dynamic code generation is the process of generating Java classes at runtime that can then be loaded into that same Java Virtual Machine (JVM) and accessed the same way as ordinary compiled Java classes. The usefulness of the technique might not be immediately apparent, but it's actually used to a great degree of success in several critical, high-profile Java technologies.

JavaServer Pages
Perhaps the best-known example of dynamic code generation in Java is JavaServer Pages (JSP). A servlet engine is capable of dispatching requests to a servlet for processing. Unfortunately, servlets are static in nature. They typically need to be precompiled and preconfigured in the servlet engine before server startup. Although they're quite useful, Web development often requires a more flexible solution.

JSP breaks these restrictions and allows servlets to be dynamically created at runtime based on the contents of a JSP file. When a request is made for a JSP file, the servlet engine makes a request to the JSP engine, which in turn will process the JSP file and send a result. A JSP is a textual representation of a set of actions to be performed to present a page to the user, and interpreting it anew for each request would be quite costly. Instead, the JSP engine will compile the JSP and dynamically create a servlet object. If the specification changes, a new servlet will be dynamically generated.

Dynamic code generation is a big win here because it brings dynamic behavior without a large performance penalty. The behavior of the runtime system doesn't need to be specified completely at compile time or even at the time the system starts. Yet, at the same time, we avoid the slothful response times that might be associated with interpreting the JSP file for each request.

A lesser known but more recent example of dynamic code generation is XSLTC. A subproject of the Apache XALAN project, XSLTC is a compiler for XSL stylesheets that can compile a stylesheet into a Java class to perform that specified transformation. XSLTC can function as a traditional compiler or can compile a stylesheet in memory to immediately process an XML input file with the full performance benefit of compiled code.

The power of this technique should not be overlooked. The flexibility of an XML-based specification (which is not necessarily available until runtime) is combined with the performance of executing Java code directly.

Methods for Code Generation
Now that we've seen two systems that make use of dynamic code generation, let's explore the code generation techniques of both systems by applying them to a simple problem domain. We'll develop a simple, four-function, stack-based integer expression evaluator with variable substitution.

Our expression evaluator will evaluate mathematical expressions such as "4 $0 + $1 *". Stack-based processing of this expression is trivial. We push 4 and variable 0 on the stack and then add the top two values on the stack, replacing both of the operands with the result of the addition. Next we push variable 1 on the stack and perform a multiple operation. In more familiar algebraic notation, this would be represented as "(4 + $0) * $1". If we were to evaluate this expression with the variable list of "[3, 6]", the result would be (4 + 3) * 6 = 42.

All of our expression evaluators will conform to the calculator interface. The calculator interface contains a single method, evaluate, that takes an array of integer arguments as input and returns the integer result of performing whatever calculation is required.

// Calculator.java
public interface Calculator
int evaluate(int[] arguments);

A Simple Expression Evaluator
For demonstration purposes, we'll consider a simple but inefficient expression interpreter that uses a Stack object to evaluate the expression (see Listing 1). The expression is parsed once for each evaluation. However, we will tokenize the expression only once, at object creation time, to avoid the overhead of the StringTokenizer class.

As you can see from the performance numbers, this method is quite slow. It may be adequate for evaluating an occasional expression, but we can do much better.

Parsing the Expression
If the expression is likely to be reused, a better technique would be to parse the expression and apply the Composite design pattern to create an expression tree (see Listing 2). The internal structure of the tree represents the logic of the expression to be evaluated.

The performance of the parsed calculator is an order of magnitude better than the simple interpreted version above. While there's still plenty of room for optimization, we're not far from the limits of what can be achieved without getting closer to the JVM.

Compiling the Expression
To make that step closer to the JVM, we'll attempt direct compilation of our expression. We'll generate a Java source file from our expression (in the same way a JSP engine would generate a Java source file) and then compile and load it.

Translating our mathematical expression into a Java expression isn't difficult. "$0 $1 $2 * +" can be represented by the Java expression "args[0] + (args[1] * args[2])". We need to choose a unique name for our class and write the generated code in a temporary file. The generated code for this expression would resemble the following:

public class [CLASSNAME]
implements Calculator
public int evaluate(int[] args) {
return args[0] + (args[1] * args[2]);
Next, we need to compile the Java code. Unfortunately, we can't count on any particular compiler to be installed on our machine. For this example we'll assume the javac compiler is available and is in our system PATH. If javac is not in our PATH or another compiler is desired, that can be specified with the "calc.compiler" property. For example, "-Dcalc.compiler=jikes".

If a compiler other than javac is used, we will almost always need to place the Java runtime JAR (rt.jar in the jre/lib directory) in the classpath passed to the compiler. We'll use the "calc.classpath" property to indicate additional classpath elements to be passed to the compiler. For example, "-Dcalc.classpath=/usr/local/java/jre/lib/rt.jar".

The compiler can be invoked as an external process using Runtime.exec(String[] cmd), which produces a Process object. The elements of the cmd array contain the system command to be executed. The first element should be the name of the program to execute. The remaining elements are the individual arguments to be passed to the compiler.

String[] cmd = {

Process process = Runtime.get

We need to wait for the compile process to end and then grab the return code from the compiler. A process return code of zero indicates a successful compile.

int val = process.exitValue();
if (val != 0) {
throw new RuntimeException(
"compile error. " +

"compiler return code is " +
One final issue with compilation is that it's important to read the output and error streams of the external process. If the compiler generates enough output, the compile process could potentially block waiting for the output to be read. We'll ignore the issue here, but this should definitely be addressed in a production system.

If the compile was successful, we now have a Java class file in the current directory that can be read in. Our ClassLoader needs a byte array to load, so we read the contents into the byte array and ask the system to create a class for us.

byte[] buf = readBytes(classname +
Class c = defineClass(buf, 0,
Our ClassLoader is the minimal ClassLoader necessary to accomplish our task. It doesn't perform all the tasks that a production-level ClassLoader would. However, it serves for demonstration purposes.

Once the class is successfully loaded, we can create an instance of the class and return it for use.

return (Calculator)
The complete code is shown in Listing 3. The runtime performance of the compiled calculator represents another order of magnitude speed improvement over our first attempt. Our same 1,000,000 evaluations run in 100-200ms instead of 1-2 seconds as in the prior example. But there's still a big performance hit in compiling the code. Invoking javac to compile the code can take 1-2 seconds, negating our performance gain. However, javac is not a very high-performance compiler. When we switch to a fast compiler such as jikes, compile time drops significantly, to 100-200ms.

Generating Bytecode Directly
The ultimate solution would retain the runtime performance of compilation without incurring the cost of invoking an external compiler. An in-memory compiler would be one option, but we can also eliminate the overhead and messiness of compilation by generating the Java bytecode in memory.

While writing Java to a file is relatively simple, the Java class file format is tricky enough that we'll want to use an external bytecode library to generate the file. For this article we use BCEL, the Bytecode Engineering Library.

Using BCEL, we first need to create a ClassGen object to represent our class. As with the compiled example, we have to define a unique classname. Unlike Java code, we need to directly declare our super class of Java.lang.Object. ACC_PUBLIC specifies that our class is public. We also need to set the ACC_SUPER access flag that all Java 1.0.2 or higher Java classes should set. Finally, we specify that our class is to implement the Calculator interface.

ClassGen classgen = new ClassGen(classname, "java.lang.Object", "", Constants.ACC_PUBLIC | Constants.ACC_SUPER, new String[] {"Calculator"});
Next, we need to ensure that our class has a default constructor. A Java compiler will normally insert a default constructor for us if no other constructors are defined. When generating bytecode directly, we need to explicitly perform these actions. Fortunately, BCEL has a convenient method for generating a default constructor.

Finally, we want to generate our int evaluate(int[] arguments) method. It's a very simple task to translate directly to bytecode since the JVM is stack-based. Our stack-based calculator translates almost directly onto bytecodes. Instructions are gathered in order of execution in the Instruction- List. We also need a reference to our class constant pool (Constant-PoolGen) in case pushing certain values requires us to create a constant pool reference.

Once the InstructionList is completed, we can proceed to create the MethodGen object. We want a public method whose return type is int and takes one argument, a list of ints. (Note that we used the internal representation for an array of ints, "[I".) Although it's not required, we'll also provide names for our parameters. In this case, our single parameter name is "args". Our method name is "evaluate". The final arguments are the classname, our instruction list, and the constant pool.

MethodGen method =
new MethodGen(Constants.ACC_
new Type[]
new String[] {"args"},
Java methods have strict requirements. For example, a method must declare how much space it requires on the operand stack and how much space it requires in the frame allocated for local variables. If these values are incorrect, the JVM will refuse to execute the method. In this example, it would be easy enough to compute these values. However, BCEL provides convenience functions that examine the bytecode and determine stack usage for us.

Now we can add our new method to the class.

The class is complete, so we can generate the associated bytecode and load the class into the JVM. Once we have the class structure in a byte array in memory, the ClassLoader can be invoked as we did for the compiled version. The complete code is available in Listing 4.

The code we generate directly performs as fast as the compiled code, but initial object creation time is significantly faster. Invoking the external compiler took (in the best case) over 100ms. Creating the class using BCEL took only 4ms on average.

Average object creation times for each type of object are shown in Table 1. I measured the total execution time for the following five expressions (see Table 2): each evaluated 1,000,000 times with slightly differing argument lists. The evaluation times for each type and expression are shown in Table 3.

Relevance of These Results
This is an admittedly contrived example. It would be quite rare for us to need to evaluate a mathematical expression a million times. However, it's not rare to have to interpret data (XML, scripting languages, query languages, reflection, etc.) at runtime, and also to want a system that performs well. Dynamic code generation is not applicable to every task, but it does appear most useful when:

  • The computation is primarily driven by a definition available at runtime
  • The computation is to be performed many times
  • It would be costly to interpret the definition directly for each execution
Compilation vs Generation
If dynamic code generation can be applied to a task, there's still the issue of whether compilation or bytecode generation is better for the task. Generating Java source code for compilation is, in general, an easier task. You're probably more familiar with Java code than with JVM instructions; debugging code for which you have source is easier than debugging pure bytecode. Furthermore, a good compiler may be able to apply compile-time optimizations that would be difficult to code by hand. However, external compilation is a very slow process and configuring the compiler and classpath makes the resulting application more difficult to manage.

Bytecode generation has the distinct advantage of being very fast. But it requires the developer to have a detailed understanding of the class file format and JVM instructions. Compilers really do a lot of behind-the-scenes grunt work in generating code. If the code generated is very complicated, you might want to think twice before trying to generate bytecodes directly.


  • Lindholm, T., and Yellin, F. (1999). The Java Virtual Machine Specification, Second Edition. Addison-Wesley.
  • BCEL: http://bcel.sourceforge.net/
  • XSLTC: http://xml.apache.org/xalan-j/xsltc/
  • More Stories By Norman Richards

    Norman Richards is a JBoss developer living in Austin, Tx. He is co-author of JBoss: A Developer's Notebook and XDoclet in Action.

    Comments (2)

    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.

    IoT & Smart Cities Stories
    Nicolas Fierro is CEO of MIMIR Blockchain Solutions. He is a programmer, technologist, and operations dev who has worked with Ethereum and blockchain since 2014. His knowledge in blockchain dates to when he performed dev ops services to the Ethereum Foundation as one the privileged few developers to work with the original core team in Switzerland.
    In his general session at 19th Cloud Expo, Manish Dixit, VP of Product and Engineering at Dice, discussed how Dice leverages data insights and tools to help both tech professionals and recruiters better understand how skills relate to each other and which skills are in high demand using interactive visualizations and salary indicator tools to maximize earning potential. Manish Dixit is VP of Product and Engineering at Dice. As the leader of the Product, Engineering and Data Sciences team at D...
    Dynatrace is an application performance management software company with products for the information technology departments and digital business owners of medium and large businesses. Building the Future of Monitoring with Artificial Intelligence. Today we can collect lots and lots of performance data. We build beautiful dashboards and even have fancy query languages to access and transform the data. Still performance data is a secret language only a couple of people understand. The more busine...
    Bill Schmarzo, author of "Big Data: Understanding How Data Powers Big Business" and "Big Data MBA: Driving Business Strategies with Data Science," is responsible for setting the strategy and defining the Big Data service offerings and capabilities for EMC Global Services Big Data Practice. As the CTO for the Big Data Practice, he is responsible for working with organizations to help them identify where and how to start their big data journeys. He's written several white papers, is an avid blogge...
    René Bostic is the Technical VP of the IBM Cloud Unit in North America. Enjoying her career with IBM during the modern millennial technological era, she is an expert in cloud computing, DevOps and emerging cloud technologies such as Blockchain. Her strengths and core competencies include a proven record of accomplishments in consensus building at all levels to assess, plan, and implement enterprise and cloud computing solutions. René is a member of the Society of Women Engineers (SWE) and a m...
    Andrew Keys is Co-Founder of ConsenSys Enterprise. He comes to ConsenSys Enterprise with capital markets, technology and entrepreneurial experience. Previously, he worked for UBS investment bank in equities analysis. Later, he was responsible for the creation and distribution of life settlement products to hedge funds and investment banks. After, he co-founded a revenue cycle management company where he learned about Bitcoin and eventually Ethereal. Andrew's role at ConsenSys Enterprise is a mul...
    Whenever a new technology hits the high points of hype, everyone starts talking about it like it will solve all their business problems. Blockchain is one of those technologies. According to Gartner's latest report on the hype cycle of emerging technologies, blockchain has just passed the peak of their hype cycle curve. If you read the news articles about it, one would think it has taken over the technology world. No disruptive technology is without its challenges and potential impediments t...
    If a machine can invent, does this mean the end of the patent system as we know it? The patent system, both in the US and Europe, allows companies to protect their inventions and helps foster innovation. However, Artificial Intelligence (AI) could be set to disrupt the patent system as we know it. This talk will examine how AI may change the patent landscape in the years to come. Furthermore, ways in which companies can best protect their AI related inventions will be examined from both a US and...
    Bill Schmarzo, Tech Chair of "Big Data | Analytics" of upcoming CloudEXPO | DXWorldEXPO New York (November 12-13, 2018, New York City) today announced the outline and schedule of the track. "The track has been designed in experience/degree order," said Schmarzo. "So, that folks who attend the entire track can leave the conference with some of the skills necessary to get their work done when they get back to their offices. It actually ties back to some work that I'm doing at the University of San...
    When talking IoT we often focus on the devices, the sensors, the hardware itself. The new smart appliances, the new smart or self-driving cars (which are amalgamations of many ‘things'). When we are looking at the world of IoT, we should take a step back, look at the big picture. What value are these devices providing. IoT is not about the devices, its about the data consumed and generated. The devices are tools, mechanisms, conduits. This paper discusses the considerations when dealing with the...