Java IoT Authors: Zakia Bouachraoui, Pat Romanski, Elizabeth White, Liz McMillan, Yeshim Deniz

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
    Moroccanoil®, the global leader in oil-infused beauty, is thrilled to announce the NEW Moroccanoil Color Depositing Masks, a collection of dual-benefit hair masks that deposit pure pigments while providing the treatment benefits of a deep conditioning mask. The collection consists of seven curated shades for commitment-free, beautifully-colored hair that looks and feels healthy.
    The textured-hair category is inarguably the hottest in the haircare space today. This has been driven by the proliferation of founder brands started by curly and coily consumers and savvy consumers who increasingly want products specifically for their texture type. This trend is underscored by the latest insights from NaturallyCurly's 2018 TextureTrends report, released today. According to the 2018 TextureTrends Report, more than 80 percent of women with curly and coily hair say they purcha...
    The textured-hair category is inarguably the hottest in the haircare space today. This has been driven by the proliferation of founder brands started by curly and coily consumers and savvy consumers who increasingly want products specifically for their texture type. This trend is underscored by the latest insights from NaturallyCurly's 2018 TextureTrends report, released today. According to the 2018 TextureTrends Report, more than 80 percent of women with curly and coily hair say they purcha...
    We all love the many benefits of natural plant oils, used as a deap treatment before shampooing, at home or at the beach, but is there an all-in-one solution for everyday intensive nutrition and modern styling?I am passionate about the benefits of natural extracts with tried-and-tested results, which I have used to develop my own brand (lemon for its acid ph, wheat germ for its fortifying action…). I wanted a product which combined caring and styling effects, and which could be used after shampo...
    The platform combines the strengths of Singtel's extensive, intelligent network capabilities with Microsoft's cloud expertise to create a unique solution that sets new standards for IoT applications," said Mr Diomedes Kastanis, Head of IoT at Singtel. "Our solution provides speed, transparency and flexibility, paving the way for a more pervasive use of IoT to accelerate enterprises' digitalisation efforts. AI-powered intelligent connectivity over Microsoft Azure will be the fastest connected pat...
    There are many examples of disruption in consumer space – Uber disrupting the cab industry, Airbnb disrupting the hospitality industry and so on; but have you wondered who is disrupting support and operations? AISERA helps make businesses and customers successful by offering consumer-like user experience for support and operations. We have built the world’s first AI-driven IT / HR / Cloud / Customer Support and Operations solution.
    Codete accelerates their clients growth through technological expertise and experience. Codite team works with organizations to meet the challenges that digitalization presents. Their clients include digital start-ups as well as established enterprises in the IT industry. To stay competitive in a highly innovative IT industry, strong R&D departments and bold spin-off initiatives is a must. Codete Data Science and Software Architects teams help corporate clients to stay up to date with the mod...
    At CloudEXPO Silicon Valley, June 24-26, 2019, Digital Transformation (DX) is a major focus with expanded DevOpsSUMMIT and FinTechEXPO programs within the DXWorldEXPO agenda. Successful transformation requires a laser focus on being data-driven and on using all the tools available that enable transformation if they plan to survive over the long term. A total of 88% of Fortune 500 companies from a generation ago are now out of business. Only 12% still survive. Similar percentages are found throug...
    Druva is the global leader in Cloud Data Protection and Management, delivering the industry's first data management-as-a-service solution that aggregates data from endpoints, servers and cloud applications and leverages the public cloud to offer a single pane of glass to enable data protection, governance and intelligence-dramatically increasing the availability and visibility of business critical information, while reducing the risk, cost and complexity of managing and protecting it. Druva's...
    BMC has unmatched experience in IT management, supporting 92 of the Forbes Global 100, and earning recognition as an ITSM Gartner Magic Quadrant Leader for five years running. Our solutions offer speed, agility, and efficiency to tackle business challenges in the areas of service management, automation, operations, and the mainframe.