<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom">
  <channel>
    <title>Java on bramp.net</title>
    <link>https://blog.bramp.net/</link>
    <description>Recent content in Java on bramp.net</description>
    <generator>Hugo -- gohugo.io</generator>
    <language>en-GB</language>
    <lastBuildDate>Sat, 13 Jan 2018 12:50:31 -0800</lastBuildDate>
    <atom:link href="https://blog.bramp.net/tags/java/" rel="self" type="application/rss+xml" />
    
    <item>
      <title>Running Java in Production: A SRE’s Perspective</title>
      <link>https://blog.bramp.net/post/2018/01/13/running-java-in-production/</link>
      <pubDate>Sat, 13 Jan 2018 12:50:31 -0800</pubDate>
      
      <guid>https://blog.bramp.net/post/2018/01/13/running-java-in-production/</guid>
      <description><p><em>Originally <a href="https://www.javaadvent.com/2017/12/running-java-in-production.html">published</a> as part of the Java Advent 2017 series</em></p>
<p>As a <a href="https://landing.google.com/sre/">Site Reliability Engineer</a> (SRE) I make sure our production services are efficient, scalable, and reliable. A typical SRE is a master of production, and has to have a good understanding of the wider architecture, and be well versed in many of the finer details.</p>
<p>It is common that SREs are polyglot programmer, expected to understand multiple different languages. For example, C++ may be hard to write, test and get right, but has high performance, perfect for backend systems such as databases. Whereas Python is easy to write, and great for quick scripting, useful for automation. Java is somewhere in the middle, and even though it is a compiled language, it provides type safety, performance, and many other advantages that make it a good choice for writing web infrastructure.</p>
<p>Even though many of the <a href="https://landing.google.com/sre/book.html">best practices that SREs adopt</a> can be generalised to any language, there are some unique challenges with Java Web applications. This article highlight some of these challenges and talks about what we can do to address them.</p>
<h1 id="deployment">Deployment</h1>
<p>A typical java application consists of 100s of class files, either written by your team, or from common libraries that the application depends on. To keep the number of class files under control, and to provide better versioning, and compartmentalisation, they are typically bundled up into <a href="https://en.wikipedia.org/wiki/JAR_(file_format)">JAR</a> or <a href="https://en.wikipedia.org/wiki/WAR_(file_format)">WAR</a> files.</p>
<p>There are many ways to host a java application, one popular method is using a <a href="https://en.wikipedia.org/wiki/Web_container">Java Servlet Container</a> such as <a href="https://tomcat.apache.org/">Tomcat</a>, or <a href="https://www.jboss.org/">JBoss</a>. These provide some common web infrastructure, and libraries to make it, in theory, easier to deploy and manage the java application. Take Tomcat, a java program that provides the actual webserver and loads the application (bundled as a WAR file) on your behalf. This may work well in some situations, but actually adds additional complexity. For example, you now need to keep track of the version of the JRE, the version of Tomcat, and the version of your application. Testing for incompatibility, and ensuring everyone is using the same versions of the full stack can be problematic, and lead to subtle problems. Tomcat also brings along its own bespoke configuration, which is yet another thing to learn.</p>
<p>A good tenant to follow is to “<a href="https://landing.google.com/sre/book/chapters/simplicity.html">keep it simple</a>”, but in the Servlet Container approach, you have to keep track of a few dozen Tomcat files, plus one or more WAR files that make up the application, plus all the Tomcat configuration that goes along with it.</p>
<p>Thus there are some frameworks that attempt to reduce this overhead by instead of being hosted within a full application server, they embed their own web server. There is still a JVM but it invokes a single JAR file that contains everything needed to run the application. Popular frameworks that enable these standalone apps are <a href="http://www.dropwizard.io/">Dropwizard</a> and <a href="https://projects.spring.io/spring-boot/">Spring Boot</a>. To deploy a new version of the application, only a single file needs to be changed, and the JVM restarted. This is also useful when developing and testing the application, because everyone is using the same version of the stack. It is also especially useful for rollbacks (one of SRE’s core tools), as only a single file has to be changed (which can be as quick as a symlink change).</p>
<p>One thing to note with a Tomcat style WAR file, the file would contain the application class files, as well as all the libraries the application depends on as JAR files. In the standalone approach, all the dependencies are merged into a single, <a href="https://stackoverflow.com/questions/19150811/what-is-a-fat-jar">Fat JAR</a>. A single JAR file that contains the class files for the entire application. These Fat or Uber JARs, not only are easier to version and copy around (because it is a single immutable file), but can actually be smaller than an equivalent WAR file due to pruning of unused classes in the dependencies.</p>
<p>This can even be taken further, by not requiring separate JVM and JAR files. Tools like <a href="http://www.capsule.io/">capsule.io</a>, can actually bundle up the JAR file, JVM, and all configuration into a single executable file. Now we can really ensure the full stack is using the same versions, and the deployment is agnostic to what may already be installed on the server.</p>
<blockquote>
<p>Keep it simple, and make the application as quick and easy to version, using a single Fat JAR, or executable where possible.</p>
</blockquote>
<h1 id="startup">Startup</h1>
<p>Even though Java is a compiled language, it is not compiled to machine code, it is instead compiled to bytecode. At runtime the Java Virtual Machine (JVM) interprets the bytecode, and executes it in the most efficient way. For example, <a href="https://en.wikipedia.org/wiki/Just-in-time_compilation">just-in-time</a> (JIT) compilation allows the JVM to watch how the application is used, and on the fly compile the bytecode into optimal machine code. Over the long run this may be advantageous for the application, but during startup can make the application perform suboptimally for tens of minutes, or longer. This is something to be aware of, as it has implications on load balancing, monitoring, capacity planning, etc.</p>
<p>In a multi-server deployment, it is best practice to slowly ramp up traffic to a newly started task, giving it time to warm up, and to not harm the overall performance of the service. You may be tempted to warm up new tasks by sending it artificial traffic, before it is placed into the user-serving path. Artificial traffic can be problematic if it does not approximate normal user traffic. In fact, this fake traffic may trigger the JIT to optimise for cases that don’t normally occur, thus leaving the application in a sub-optimal or worse state than not being JIT’d.</p>
<p>Slow starts should also be considered when capacity planning. Don’t expect cold tasks to handle the same load as warm tasks. This is important when rolling out a new version of the application, as the capacity of the system will drop until the tasks warms up. If this is not taken into account, too many tasks may be reloaded concurrently, causing a capacity based cascading outage.</p>
<blockquote>
<p>Expect cold starts, and try to warm the application up with real traffic.</p>
</blockquote>
<h1 id="monitoring">Monitoring</h1>
<p>This advice is generic <a href="https://landing.google.com/sre/book/chapters/monitoring-distributed-systems.html">monitoring advice</a>, but it is worth repeating for Java. Make sure the most important and useful metrics are exported from the Java application, are collected and easily graphed. There are many tools and frameworks for exporting metrics, and even more for collecting, aggregating, and displaying.</p>
<p>When something breaks, <a href="https://landing.google.com/sre/book/chapters/effective-troubleshooting.html">troubleshooting</a> the issue should be possible from only the metrics being collected. You should not be to depending on log files, or looking at code, to deal with an outage.</p>
<p>Most outages are caused by change. That is, a new version of the application, a config change, new source of traffic, a hardware failure, or a backend dependencies behaving differently. The metrics exported by the application, should include ways to identify the version of Java, application, and configuration in use. It should break down sources of traffic, mix, error counts, etc. It should also track the health, latency, error rates, etc of backend dependencies. Most of the time, this is enough to diagnose a outage quickly.</p>
<p>Specific to Java, there are metrics that can be helpful to understand the health, and performance of the application. Guiding future decisions on how to scale and optimise the application. Garbage collection time, heap size, thread count, JIT time are all important and Java specific.</p>
<p>Finally, a note about measuring response times, or latency. That is, the time it takes the application to handle a request. Many make the mistake of looking at average latency, in part because it can be easily calculated. <a href="https://www.elastic.co/blog/averages-can-dangerous-use-percentile">Averages can be misleading</a>, because it doesn’t show the <a href="https://en.wikipedia.org/wiki/Percentile_rank">shape of the distribution</a>. The majority of requests may be handled quickly, but there may be a long tail of requests that are rare but take a while. This is especially troubling for JVM application, because during garbage collection there is a <a href="https://www.cubrid.org/blog/understanding-java-garbage-collection">stop the world</a> (STW) phase, where the application must pause, to allow the garbage collection to finish. In this pause, no requests will be responded to, and users may wait multiple seconds.</p>
<p>It is better to collect either the max, or 99 (or higher) percentile latency. For percentile, that say for every every 100 requests, 99 are served quicker than this number. Looking at the worst case latency is more meaningful, and more reflective of the user perceived performance.</p>
<blockquote>
<p>Measure metrics that matter, and you can later depend on.</p>
</blockquote>
<h1 id="memory-management">Memory Management</h1>
<p>A good investment of your time is to learn about the various <a href="https://plumbr.io/handbook/garbage-collection-algorithms-implementations">JVM garbage collection algorithms</a>. The current state of the art are the concurrent collectors, either <a href="https://www.redhat.com/en/blog/part-1-introduction-g1-garbage-collector">G1</a>, or <a href="https://docs.oracle.com/javase/8/docs/technotes/guides/vm/gctuning/cms.html">CMS</a>. You can decide on what may be best for your application, but for now G1 is the likely winner. There are many great articles that explain how they work, but I’ll cover some key topics.</p>
<p>When starting up, the Java Virtual Machine (JVM) reserves a large chunk of OS memory and splits it into heap and non-heap. The non-heap contains areas such as <a href="https://blogs.oracle.com/poonam/about-g1-garbage-collector,-permanent-generation-and-metaspace">Metaspace</a> (<a href="https://dzone.com/articles/java-8-permgen-metaspace">formally called Permgen</a>), and stack space. Metaspace is for class definitions, and stack space is for each thread&rsquo;s stacks. The heap is used for the objects that are created, which normally takes up the majority of the memory usage. Unlike a typical executable, the JVM has the <a href="https://alvinalexander.com/blog/post/java/java-xmx-xms-memory-heap-size-control"><code>-Xms</code> and <code>-Xmx</code> flags</a> that control the minimum and maximum size of the heap. These limits constrain the maximum amount of RAM the JVM will use, which can make the memory demands on your servers predictable. It is common to set both these flags to the same value, provisioning them to fill up the available RAM on your server. There are also best practices around this when <a href="https://developers.redhat.com/blog/2017/03/14/java-inside-docker/">sizing Docker containers</a>.</p>
<p>Garbage collection (GC) is the process of managing this heap, by finding java objects that are no longer in use (i.e no longer referred to), and can be reclaimed. In most cases the JVM scans the full graph of objects, marking which it finds. At the end, any that weren’t visited, are deleted. To ensure there aren’t race conditions, the GC typically has to stop the world (STW), which pauses the application for a short while, while it finishes up.</p>
<p>The GC is a source of (perhaps unwarranted) resentment because it is blamed for many performance problems. Typically this boils down to not understanding how the GC works. For example, if the heap is sized too small, the JVM can aggressive garbage collect, trying to futilely free up space. The application can then get stuck in this “<a href="http://javaagile.blogspot.com/2013/07/the-thrashing-of-garbage-collector.html">GC thrashing</a>” cycle, that makes very little progress freeing up space, and spending a larger and larger proportion of time in GC, instead of running the application code.</p>
<p>Two common cases where this can happen, are <a href="https://plumbr.io/blog/memory-leaks/what-is-a-memory-leak">memory leaks</a>, or <a href="http://www.oracle.com/technetwork/articles/java/trywithresources-401775.html">resource exhaustion</a>. Garbage collected languages shouldn’t allow what is conventionally called memory leaks, however, they can occur. Take for example, maintaining a cache of objects that never expire. This cache will grow forever, and even though the objects in the cache may never be used again, they are still referenced, thus ineligible to be garbage collected.</p>
<p>Another common cases is <a href="https://blog.bramp.net/post/2015/12/17/the-importance-of-tuning-your-thread-pools/">unbounded queues</a>. If your application places incoming requests on a unbounded queue, this queue could grow forever. If there is a spike of request, objects retained on the queue could increase the heap usage, causing the application to spend more and more time in GC. Thus the application will have less time to process requests from the queue, causing the backlog to grow. This spirals out of control as the GC struggles to find any objects to free, until the application can make no forward progress.</p>
<p>The garbage collector algorithms has many optimisations to try and reduce total GC time. One important observation, the <a href="https://docs.oracle.com/javase/8/docs/technotes/guides/vm/gctuning/generations.html">weak generational hypothesis</a>, is that objects either exist for a short time (for example, related to the handling a request), or last a long time (such as global objects that manage long lived resources).</p>
<p>Because of this, the heap is further divided into young and old space. The GC algorithm that runs across the young space assume the object will be freed, and if not, the GC promotes the object into old space. The algorithm for old space, makes the opposite assumption, the the object won’t be freed. The size of the <a href="https://docs.oracle.com/javase/8/docs/technotes/guides/vm/gctuning/sizing.html">young/old may thus also be tuned</a>, and depending on G1 or CMS the approach will be different. But, if the young space is too small, objects that should only exist for short time end up getting promoted to old space. Breaking some of the assumptions the old GC algorithms make, causing GC to run less efficiently, and causing secondary issues such as memory fragmentation.</p>
<p>As mentioned earlier, GC is a source of <a href="https://www.weave.works/blog/the-long-tail-tools-to-investigate-high-long-tail-latency/">long tail latency</a>, so should be monitored closely. The time taken for each phase of the GC should be recorded, as well as the fullness of heap space (broken down by young/old/etc) before and after GC runs. This provides all the hints needed to either tune, or improve the application to get GC under control.</p>
<blockquote>
<p>Make GC your friend. Careful attention should be paid to the heap, and garbage collector, and it should be tuned (even coarsely) to ensure there is enough heap space even in the fully loaded/worst case.</p>
</blockquote>
<h1 id="other-tips">Other tips</h1>
<h2 id="debugging">Debugging</h2>
<p>Java has many rich tools for debugging during development and in production. For example, it is possible to capture live stack traces, and heap dumps from the running application. This can be useful to understand memory leaks, or deadlocks. However, you must ensure the application is started to allow these features, and that the typical tools, <a href="https://docs.oracle.com/javase/6/docs/technotes/tools/share/jmap.html">jmap</a>, <a href="https://docs.oracle.com/javase/8/docs/technotes/guides/troubleshoot/tooldescr006.html">jcmd</a>, etc are actually available on the server. Running the application inside a <a href="http://trustmeiamadeveloper.com/2016/03/18/where-is-my-memory-java/">Docker container</a>, or non-standard environment, may make this more difficult, so test and write a playbook on how to do this now.</p>
<p>Many frameworks, also expose much of this information via webservices, for easier debugging, for example the Dropwizard /threads resource, or the <a href="https://docs.spring.io/spring-boot/docs/current/reference/html/production-ready-endpoints.html">Spring Boot production endpoints</a>.</p>
<blockquote>
<p>Don’t wait until you have a production issue, test now how to grab heap dumps and stack traces.</p>
</blockquote>
<h2 id="fewer-but-larger-tasks">Fewer but larger tasks</h2>
<p>There are many features of the JVM that have a fixed cost per running JVM, such as JIT and garbage collection. Your application may also have fixed overheads, such as resource polling (backend database connections), etc. If you run fewer, but larger (in terms of CPU and RAM) instances, you can reduce this fixed cost, getting an economy of scale. I’ve seen doubling the amount of CPU and RAM a Java application had, allowed it to handle 4x the requests per second (with no impact to latency). This however makes some assumption about the application’s ability to scale in a multi-threaded way, but generally scaling vertically is easier than horizontally.</p>
<blockquote>
<p>Make your JVM as large as possible.</p>
</blockquote>
<h2 id="32-bit-vs-64-bit-java">32-bit vs. 64-bit Java</h2>
<p>It used to be common practice to run a 32-bit JVM if your application didn’t use more than 4GiB of RAM. This was because 32-bit pointers are half the size of 64-bit, which reduced the overhead of each java object. However, as modern CPUs are 64-bit, typically with 64-bit specific performance improvements, and that the cost of RAM being cheap this make 64-bit JVMs the clear winner.</p>
<blockquote>
<p>Use 64-bit JVMs.</p>
</blockquote>
<h2 id="load-shedding">Load Shedding</h2>
<p>Again general advice, but important for java. To <a href="https://landing.google.com/sre/book/chapters/handling-overload.html">avoid overload</a> caused by GC thrashing, or cold tasks, the application should aggressively load shed. That is, beyond some threshold, the application should reject new requests. It may seem bad to reject some requests early, but it is better than allowing the application to become unrecoverably unhealthy and fail all requests. There are many ways to avoid overload, but common approaches are to ensure queues are bounded, and that <a href="https://blog.bramp.net/post/2015/12/17/the-importance-of-tuning-your-thread-pools/">thread pools are sized correctly</a>. Additionally, outbound request should have <a href="https://www.datawire.io/guide/traffic/deadlines-distributed-timeouts-microservices/">appropriate deadlines</a>, to ensure a slow backend doesn’t cause problems for your application.</p>
<blockquote>
<p>Handle as many requests as you can, and no more.</p>
</blockquote>
<h1 id="conclusion">Conclusion</h1>
<p>Hopefully this article has made you think about your java production environment. While not be prescriptive, we highlight some areas to focus. The links throughout should guide you in the right direction.</p>
</description>
    </item>
    
    <item>
      <title>Maven Plugins on Java 8</title>
      <link>https://blog.bramp.net/post/2017/04/01/maven-plugins-on-java-8/</link>
      <pubDate>Sat, 01 Apr 2017 15:21:27 -0700</pubDate>
      
      <guid>https://blog.bramp.net/post/2017/04/01/maven-plugins-on-java-8/</guid>
      <description><p>As part of my standard Maven configuration, I like to use two plugins backed by Google technologies, the first to help keep my code formatted correctly, and the second to check for compile time errors. However, Google recently moved to require JDK 1.8, which broke anyone trying to compile my projects with an older JDK. In this article I&rsquo;ll quickly explain how to configure Maven to work around this problem.</p>
<p>Specifically I use the following two plugins:</p>
<ul>
<li>
<p><a href="https://github.com/coveo/fmt-maven-plugin">coveo/fmt-maven-plugin</a> (which uses <a href="https://github.com/google/google-java-format">google-java-format</a>). This follows the <a href="https://google.github.io/styleguide/javaguide.html">Google&rsquo;s Java Style</a> guide, and reformats the code to ensure it stays consistent. This is great when accepting external contributions, as it keeps the code base uniform, and avoids style discussion on pull requests.</p>
</li>
<li>
<p><a href="https://github.com/codehaus-plexus/plexus-compiler">plexus-compiler-javac-errorprone</a> (which uses Google&rsquo;s <a href="https://github.com/google/error-prone">errorprone</a>). This is a static code analysis tool, that checks for simple errors at compile time, and fails the build if they are found. Again, this helps improve the quality of the code.</p>
</li>
</ul>
<p>Even though my projects typically target 1.7, these plugins require to run under 1.8. Really I&rsquo;d prefer I could bump all my projects to target 1.8+, but since a few of my projects are libraries (which other people include into their projects), that is easier said than done. To deal with this, I changed my Maven configuration to only run these two plugins when run under the sufficient JDK. This means those using a older JDK don&rsquo;t get the benefits, but since locally I use JDK 8, and all my open source projects use <a href="https://travis-ci.org">Travis CI</a>, eventually these issues will be identified.</p>
<p>So if you get an error like</p>
<pre tabindex="0"><code>java.lang.UnsupportedClassVersionError: com/google/googlejavaformat/java/FormatterException : Unsupported major.minor version 52.0
</code></pre><p>or</p>
<pre tabindex="0"><code>An API incompatibility was encountered while executing org.apache.maven.plugins:maven-compiler-plugin:3.5.1:compile: java.lang.UnsupportedClassVersionError: javax/tools/DiagnosticListener : Unsupported major.minor version 52.0
</code></pre><p>Please update to JDK 1.8, or update your Maven configuration to restrict these plugins to when run on a modern JDK:</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-xml" data-lang="xml"><span class="line"><span class="cl"><span class="nt">&lt;project&gt;</span>
</span></span><span class="line"><span class="cl">...
</span></span><span class="line"><span class="cl">    <span class="nt">&lt;profiles&gt;</span>
</span></span><span class="line"><span class="cl">        <span class="nt">&lt;profile&gt;</span>
</span></span><span class="line"><span class="cl">            <span class="nt">&lt;id&gt;</span>java18<span class="nt">&lt;/id&gt;</span>
</span></span><span class="line"><span class="cl">            <span class="nt">&lt;activation&gt;</span>
</span></span><span class="line"><span class="cl">                <span class="nt">&lt;jdk&gt;</span>1.8<span class="nt">&lt;/jdk&gt;</span>
</span></span><span class="line"><span class="cl">            <span class="nt">&lt;/activation&gt;</span>
</span></span><span class="line"><span class="cl">            <span class="nt">&lt;build&gt;</span>
</span></span><span class="line"><span class="cl">                <span class="nt">&lt;plugins&gt;</span>
</span></span><span class="line"><span class="cl">                    <span class="nt">&lt;plugin&gt;</span>
</span></span><span class="line"><span class="cl">                        <span class="nt">&lt;groupId&gt;</span>com.coveo<span class="nt">&lt;/groupId&gt;</span>
</span></span><span class="line"><span class="cl">                        <span class="nt">&lt;artifactId&gt;</span>fmt-maven-plugin<span class="nt">&lt;/artifactId&gt;</span>
</span></span><span class="line"><span class="cl">                        <span class="nt">&lt;executions&gt;</span>
</span></span><span class="line"><span class="cl">                            <span class="nt">&lt;execution&gt;</span>
</span></span><span class="line"><span class="cl">                                <span class="nt">&lt;goals&gt;</span>
</span></span><span class="line"><span class="cl">                                    <span class="nt">&lt;goal&gt;</span>format<span class="nt">&lt;/goal&gt;</span>
</span></span><span class="line"><span class="cl">                                <span class="nt">&lt;/goals&gt;</span>
</span></span><span class="line"><span class="cl">                            <span class="nt">&lt;/execution&gt;</span>
</span></span><span class="line"><span class="cl">                        <span class="nt">&lt;/executions&gt;</span>
</span></span><span class="line"><span class="cl">                    <span class="nt">&lt;/plugin&gt;</span>
</span></span><span class="line"><span class="cl">                    <span class="nt">&lt;plugin&gt;</span>
</span></span><span class="line"><span class="cl">                        <span class="nt">&lt;groupId&gt;</span>org.apache.maven.plugins<span class="nt">&lt;/groupId&gt;</span>
</span></span><span class="line"><span class="cl">                        <span class="nt">&lt;artifactId&gt;</span>maven-compiler-plugin<span class="nt">&lt;/artifactId&gt;</span>
</span></span><span class="line"><span class="cl">                        <span class="nt">&lt;configuration&gt;</span>
</span></span><span class="line"><span class="cl">                            <span class="nt">&lt;compilerId&gt;</span>javac-with-errorprone<span class="nt">&lt;/compilerId&gt;</span>
</span></span><span class="line"><span class="cl">                            <span class="nt">&lt;forceJavacCompilerUse&gt;</span>true<span class="nt">&lt;/forceJavacCompilerUse&gt;</span>
</span></span><span class="line"><span class="cl">                            <span class="nt">&lt;showWarnings&gt;</span>true<span class="nt">&lt;/showWarnings&gt;</span>
</span></span><span class="line"><span class="cl">                            <span class="nt">&lt;compilerArgs&gt;</span>
</span></span><span class="line"><span class="cl">                                <span class="nt">&lt;arg&gt;</span>-Xlint:all<span class="nt">&lt;/arg&gt;</span>
</span></span><span class="line"><span class="cl">                            <span class="nt">&lt;/compilerArgs&gt;</span>
</span></span><span class="line"><span class="cl">                        <span class="nt">&lt;/configuration&gt;</span>
</span></span><span class="line"><span class="cl">                        <span class="nt">&lt;dependencies&gt;</span>
</span></span><span class="line"><span class="cl">                            <span class="nt">&lt;dependency&gt;</span>
</span></span><span class="line"><span class="cl">                                <span class="nt">&lt;groupId&gt;</span>org.codehaus.plexus<span class="nt">&lt;/groupId&gt;</span>
</span></span><span class="line"><span class="cl">                                <span class="nt">&lt;artifactId&gt;</span>plexus-compiler-javac-errorprone<span class="nt">&lt;/artifactId&gt;</span>
</span></span><span class="line"><span class="cl">                                <span class="nt">&lt;version&gt;</span>2.8.1<span class="nt">&lt;/version&gt;</span>
</span></span><span class="line"><span class="cl">                            <span class="nt">&lt;/dependency&gt;</span>
</span></span><span class="line"><span class="cl">                            <span class="c">&lt;!-- override plexus-compiler-javac-errorprone&#39;s dependency on
</span></span></span><span class="line"><span class="cl"><span class="c">                                 Error Prone with the latest version --&gt;</span>
</span></span><span class="line"><span class="cl">                            <span class="nt">&lt;dependency&gt;</span>
</span></span><span class="line"><span class="cl">                                <span class="nt">&lt;groupId&gt;</span>com.google.errorprone<span class="nt">&lt;/groupId&gt;</span>
</span></span><span class="line"><span class="cl">                                <span class="nt">&lt;artifactId&gt;</span>error_prone_core<span class="nt">&lt;/artifactId&gt;</span>
</span></span><span class="line"><span class="cl">                                <span class="nt">&lt;version&gt;</span>2.0.19<span class="nt">&lt;/version&gt;</span>
</span></span><span class="line"><span class="cl">                            <span class="nt">&lt;/dependency&gt;</span>
</span></span><span class="line"><span class="cl">                        <span class="nt">&lt;/dependencies&gt;</span>
</span></span><span class="line"><span class="cl">                    <span class="nt">&lt;/plugin&gt;</span>
</span></span><span class="line"><span class="cl">                <span class="nt">&lt;/plugins&gt;</span>
</span></span><span class="line"><span class="cl">            <span class="nt">&lt;/build&gt;</span>
</span></span><span class="line"><span class="cl">        <span class="nt">&lt;/profile&gt;</span>
</span></span><span class="line"><span class="cl">    <span class="nt">&lt;/profiles&gt;</span>
</span></span><span class="line"><span class="cl">...
</span></span><span class="line"><span class="cl"><span class="nt">&lt;/project&gt;</span>
</span></span></code></pre></div><p>This defines a new profile, that is only &ldquo;activated&rdquo; under Java 1.8. When activated the <code>&lt;build&gt;</code> section has the two additional plugins added.
Ensure that these plugins are no longer mentioned in the regular <code>&lt;build&gt;</code> section, and only in the <code>&lt;profile&gt;&lt;build&gt;</code> section.</p>
<p>An example of this change can be found in <a href="https://github.com/bramp/ffmpeg-cli-wrapper/commit/4985ba3ab3ef84839bc0f4ca8b63573b77e33c67">recent commit</a>.</p>
</description>
    </item>
    
    <item>
      <title>The importance of tuning your thread pools</title>
      <link>https://blog.bramp.net/post/2015/12/17/the-importance-of-tuning-your-thread-pools/</link>
      <pubDate>Thu, 17 Dec 2015 01:00:00 +0000</pubDate>
      
      <guid>https://blog.bramp.net/post/2015/12/17/the-importance-of-tuning-your-thread-pools/</guid>
      <description><p><em>Originally <a href="http://www.javaadvent.com/2015/12/the-importance-of-tuning-your-thread-pools.html">published</a> as part of the Java Advent 2015 series</em></p>
<p>Whether you know it or not, your Java web application is most likely using a thread pool to handle incoming requests. This is an implementation detail that many overlook, but sooner or later you will need to understand how the pool is used, and how to correctly tune it for your application. This article aims to explain the threaded model, what a thread pool is, and what you need to do to correctly configure them.</p>
<h2 id="single-threaded">Single Threaded</h2>
<p>Let us start with some basics, and progress with the evolution of the threaded model. No matter which application server or framework you use, <a href="https://tomcat.apache.org/">Tomcat</a>, <a href="http://www.dropwizard.io/">Dropwizard</a>, <a href="https://eclipse.org/jetty/">Jetty</a>, they all use the same fundamental approach. Buried deep inside the web server is a socket. This socket is listening for incoming TCP connections, and accepting them. Once accepted, data can be read from the newly established TCP connection, parsed, and turned into a HTTP request. This request is then handed off to the web application, to do with what it wants.</p>
<p>To provide an understanding of the role of threads, we won’t use an application server, instead we will build a simple server from scratch. This server mirrors what most application servers do under the hood. To start with, a single threaded web server may look like this:</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="line"><span class="cl"><span class="n">ServerSocket</span><span class="w"> </span><span class="n">listener</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="k">new</span><span class="w"> </span><span class="n">ServerSocket</span><span class="p">(</span><span class="n">8080</span><span class="p">);</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="k">try</span><span class="w"> </span><span class="p">{</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">	</span><span class="k">while</span><span class="w"> </span><span class="p">(</span><span class="kc">true</span><span class="p">)</span><span class="w"> </span><span class="p">{</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">		</span><span class="n">Socket</span><span class="w"> </span><span class="n">socket</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="n">listener</span><span class="p">.</span><span class="na">accept</span><span class="p">();</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">		</span><span class="k">try</span><span class="w"> </span><span class="p">{</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">			</span><span class="n">handleRequest</span><span class="p">(</span><span class="n">socket</span><span class="p">);</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">		</span><span class="p">}</span><span class="w"> </span><span class="k">catch</span><span class="w"> </span><span class="p">(</span><span class="n">IOException</span><span class="w"> </span><span class="n">e</span><span class="p">)</span><span class="w"> </span><span class="p">{</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">			</span><span class="n">e</span><span class="p">.</span><span class="na">printStackTrace</span><span class="p">();</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">		</span><span class="p">}</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">	</span><span class="p">}</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="p">}</span><span class="w"> </span><span class="k">finally</span><span class="w"> </span><span class="p">{</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">	</span><span class="n">listener</span><span class="p">.</span><span class="na">close</span><span class="p">();</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="p">}</span><span class="w">
</span></span></span></code></pre></div><p>This code creates a <a href="https://docs.oracle.com/javase/7/docs/api/java/net/ServerSocket.html">ServerSocket</a> on port 8080, then in a tight loop the ServerSocket checks for new connections to accept. Once accepted the socket is passed to a handleRequest method. That method would typically read the HTTP request, do whatever process is needed, and write a response. In this simple example, handleRequest reads a single line, and returns a short HTTP response. It would be normal for handleRequest to do something more complex, such as reading from a database, or conducting some other kind of IO.</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="line"><span class="cl"><span class="kd">final</span><span class="w"> </span><span class="kd">static</span><span class="w"> </span><span class="n">String</span><span class="w"> </span><span class="n">response</span><span class="w"> </span><span class="o">=</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">	</span><span class="s">&#34;HTTP/1.0 200 OK\r\n&#34;</span><span class="w"> </span><span class="o">+</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">	</span><span class="s">&#34;Content-type: text/plain\r\n&#34;</span><span class="w"> </span><span class="o">+</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">	</span><span class="s">&#34;\r\n&#34;</span><span class="w"> </span><span class="o">+</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">	</span><span class="s">&#34;Hello World\r\n&#34;</span><span class="p">;</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="kd">public</span><span class="w"> </span><span class="kd">static</span><span class="w"> </span><span class="kt">void</span><span class="w"> </span><span class="nf">handleRequest</span><span class="p">(</span><span class="n">Socket</span><span class="w"> </span><span class="n">socket</span><span class="p">)</span><span class="w"> </span><span class="kd">throws</span><span class="w"> </span><span class="n">IOException</span><span class="w"> </span><span class="p">{</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">	</span><span class="c1">// Read the input stream, and return &#34;200 OK&#34;</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">	</span><span class="k">try</span><span class="w"> </span><span class="p">{</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">		</span><span class="n">BufferedReader</span><span class="w"> </span><span class="n">in</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="k">new</span><span class="w"> </span><span class="n">BufferedReader</span><span class="p">(</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">			</span><span class="k">new</span><span class="w"> </span><span class="n">InputStreamReader</span><span class="p">(</span><span class="n">socket</span><span class="p">.</span><span class="na">getInputStream</span><span class="p">()));</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">		
</span></span></span><span class="line"><span class="cl"><span class="w">		</span><span class="n">log</span><span class="p">.</span><span class="na">info</span><span class="p">(</span><span class="n">in</span><span class="p">.</span><span class="na">readLine</span><span class="p">());</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">		</span><span class="n">OutputStream</span><span class="w"> </span><span class="n">out</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="n">socket</span><span class="p">.</span><span class="na">getOutputStream</span><span class="p">();</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">		</span><span class="n">out</span><span class="p">.</span><span class="na">write</span><span class="p">(</span><span class="n">response</span><span class="p">.</span><span class="na">getBytes</span><span class="p">(</span><span class="n">StandardCharsets</span><span class="p">.</span><span class="na">UTF_8</span><span class="p">));</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">	</span><span class="p">}</span><span class="w"> </span><span class="k">finally</span><span class="w"> </span><span class="p">{</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">		</span><span class="n">socket</span><span class="p">.</span><span class="na">close</span><span class="p">();</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">	</span><span class="p">}</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="p">}</span><span class="w">
</span></span></span></code></pre></div><p>As there is only a single thread handling all accepted sockets, each request must be fully handled, before accepting the next.  In a real application it could be normal for the equivalent handleRequest method to take on the order of 100 milliseconds to return. If this was the case, the server would be limited to handling only 10 requests per second, one after the other.</p>
<h2 id="multi-threaded">Multi-threaded</h2>
<p>Even though handleRequest may be blocked on IO, the CPU is free to handle more requests. With a single threaded approach this is not possible. Thus this server can be improved to allow concurrent operations, via creating multiple threads:</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="line"><span class="cl"><span class="kd">public</span><span class="w"> </span><span class="kd">static</span><span class="w"> </span><span class="kd">class</span> <span class="nc">HandleRequestRunnable</span><span class="w"> </span><span class="kd">implements</span><span class="w"> </span><span class="n">Runnable</span><span class="w"> </span><span class="p">{</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">	</span><span class="kd">final</span><span class="w"> </span><span class="n">Socket</span><span class="w"> </span><span class="n">socket</span><span class="p">;</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">	</span><span class="kd">public</span><span class="w"> </span><span class="nf">HandleRequestRunnable</span><span class="p">(</span><span class="n">Socket</span><span class="w"> </span><span class="n">socket</span><span class="p">)</span><span class="w"> </span><span class="p">{</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">		</span><span class="k">this</span><span class="p">.</span><span class="na">socket</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="n">socket</span><span class="p">;</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">	</span><span class="p">}</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">	</span><span class="kd">public</span><span class="w"> </span><span class="kt">void</span><span class="w"> </span><span class="nf">run</span><span class="p">()</span><span class="w"> </span><span class="p">{</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">		</span><span class="k">try</span><span class="w"> </span><span class="p">{</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">			</span><span class="n">handleRequest</span><span class="p">(</span><span class="n">socket</span><span class="p">);</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">		</span><span class="p">}</span><span class="w"> </span><span class="k">catch</span><span class="w"> </span><span class="p">(</span><span class="n">IOException</span><span class="w"> </span><span class="n">e</span><span class="p">)</span><span class="w"> </span><span class="p">{</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">			</span><span class="n">e</span><span class="p">.</span><span class="na">printStackTrace</span><span class="p">();</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">		</span><span class="p">}</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">	</span><span class="p">}</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="p">}</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="c1">// Main loop here</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="n">ServerSocket</span><span class="w"> </span><span class="n">listener</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="k">new</span><span class="w"> </span><span class="n">ServerSocket</span><span class="p">(</span><span class="n">8080</span><span class="p">);</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="k">try</span><span class="w"> </span><span class="p">{</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">	</span><span class="k">while</span><span class="w"> </span><span class="p">(</span><span class="kc">true</span><span class="p">)</span><span class="w"> </span><span class="p">{</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">		</span><span class="n">Socket</span><span class="w"> </span><span class="n">socket</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="n">listener</span><span class="p">.</span><span class="na">accept</span><span class="p">();</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">		</span><span class="k">new</span><span class="w"> </span><span class="n">Thread</span><span class="p">(</span><span class="w"> </span><span class="k">new</span><span class="w"> </span><span class="n">HandleRequestRunnable</span><span class="p">(</span><span class="n">socket</span><span class="p">)</span><span class="w"> </span><span class="p">).</span><span class="na">start</span><span class="p">();</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">	</span><span class="p">}</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="p">}</span><span class="w"> </span><span class="k">finally</span><span class="w"> </span><span class="p">{</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">	</span><span class="n">listener</span><span class="p">.</span><span class="na">close</span><span class="p">();</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="p">}</span><span class="w">
</span></span></span></code></pre></div><p>Here, accept() is still called in a tight loop within a single thread, but once a TCP connection is accepted, and a socket available, a new thread is spawned. This spawned thread executes a HandleRequestRunnable, which simply calls the same handleRequest method from above.</p>
<p>Creating the new thread, now frees up the original accept() thread to handle more TCP connections, and allows the application to handle requests concurrently. This technique is referred to as a “thread per request”, and is the most popular approach taken. It is worth noting there are other approaches, such as the event driven asynchronous model <a href="https://www.nginx.com/">NGINX</a> and <a href="https://nodejs.org/">Node.js</a> deploy, but they don’t use thread pools, and thus are out of scope for this article.</p>
<p>In the thread per request approach, creating a new thread (and later destroying it) can be expensive, as both the JVM and the OS needs to allocate resources. Additionally in the above implementation, the number of threads being created is unbounded. Being unbounded is very problematic, as it can quickly led to resource exhaustion.</p>
<h2 id="resource-exhaustion">Resource exhaustion</h2>
<p>Each thread requires a certain amount of memory for the stack. On recent 64bit JVMs, the <a href="https://docs.oracle.com/javase/8/docs/technotes/tools/unix/java.html">default stack size</a> is 1024KB. If the server receives a flood of requests, or the handleRequest method becomes slow, the server may end up with huge number of concurrent threads. Thus to manage 1000 concurrent requests, the 1000 threads would consume 1GB of the JVM’s RAM just for thread’s stacks. In addition the code executing in each thread will be creating objects on the heap needed to process the request. This very quickly adds up, and can exceed the heap space assigned to the JVM, putting pressure on the garbage collector, causing thrashing and eventually leading to <a href="https://docs.oracle.com/javase/7/docs/api/java/lang/OutOfMemoryError.html">OutOfMemoryErrors</a>.</p>
<p>Not only consuming RAM, the threads may use other finite resources, such as file handles, or database connections. Exceeding these may led to other types of errors or crashes. Thus to avoid exhausting resources it is important to avoid unbounded data structures.</p>
<p>Not a panacea, but the stack size issue can be somewhat mitigated by tuning the stack size with the -Xss flag. A smaller stack will reduce the per thread overhead, but potentially leads to <a href="https://docs.oracle.com/javase/7/docs/api/java/lang/StackOverflowError.html">StackOverflowErrors</a>. Your mileage will vary, but for many applications the default 1024KB is excessive, and smaller 256KB or 512KB values might be more appropriate. The smallest value Java will allow is 160KB.</p>
<h2 id="thread-pool">Thread pool</h2>
<p>To avoid continuously creating new threads, and to bound the maximum number, a simple thread pool can be used. Simply put, the pool keeps track of all threads, creating new ones when needed up to an upper bound, and where possible reusing idle threads.</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="line"><span class="cl"><span class="n">ServerSocket</span><span class="w"> </span><span class="n">listener</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="k">new</span><span class="w"> </span><span class="n">ServerSocket</span><span class="p">(</span><span class="n">8080</span><span class="p">);</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="n">ExecutorService</span><span class="w"> </span><span class="n">executor</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="n">Executors</span><span class="p">.</span><span class="na">newFixedThreadPool</span><span class="p">(</span><span class="n">4</span><span class="p">);</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="k">try</span><span class="w"> </span><span class="p">{</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">	</span><span class="k">while</span><span class="w"> </span><span class="p">(</span><span class="kc">true</span><span class="p">)</span><span class="w"> </span><span class="p">{</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">		</span><span class="n">Socket</span><span class="w"> </span><span class="n">socket</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="n">listener</span><span class="p">.</span><span class="na">accept</span><span class="p">();</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">		</span><span class="n">executor</span><span class="p">.</span><span class="na">submit</span><span class="p">(</span><span class="w"> </span><span class="k">new</span><span class="w"> </span><span class="n">HandleRequestRunnable</span><span class="p">(</span><span class="n">socket</span><span class="p">)</span><span class="w"> </span><span class="p">);</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">	</span><span class="p">}</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="p">}</span><span class="w"> </span><span class="k">finally</span><span class="w"> </span><span class="p">{</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">	</span><span class="n">listener</span><span class="p">.</span><span class="na">close</span><span class="p">();</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="p">}</span><span class="w">
</span></span></span></code></pre></div><p>Now, instead of directly creating threads, this code uses an ExecutorService, which submits work (in the term of Runnables) to be executed across a pool of threads. In this example a fixed thread pool of four threads is used to handle all incoming requests. This bounds the number of “in-flight” requests, and thus places bounds on the resource usage.</p>
<p>In addition to <a href="https://docs.oracle.com/javase/7/docs/api/java/util/concurrent/Executors.html#newFixedThreadPool(int)">newFixedThreadPool</a>, the Executors utility class also provides a <a href="https://docs.oracle.com/javase/7/docs/api/java/util/concurrent/Executors.html#newCachedThreadPool()">newCachedThreadPool</a> method. This suffers from the earlier unbounded number of threads, but whenever possible makes use of previously created but now idle threads. Typically this type of pool is useful for short-lived requests that do not block on external resources.</p>
<p><a href="https://docs.oracle.com/javase/7/docs/api/java/util/concurrent/ThreadPoolExecutor.html">ThreadPoolExecutors</a> can be constructed directly, allowing for its behaviour to be customised. For example, the min and max number of threads within the pool can be defined, as well as policies for when threads are created and destroyed. An example of this is shown shortly.</p>
<h2 id="work-queue">Work queue</h2>
<p>In the fixed thread pool case, the observant reader may wonder what happens if all threads are busy, and a new request comes in. Well the ThreadPoolExecutor may use a queue to hold pending requests before a thread becomes available. The Executors.newFixedThreadPool by default use an unbounded LinkedList. Again this leads to the resource exhaustion problem, albeit much slower since each queued request is smaller than a full thread, and will typically not be using as many resources. However, in our examples, each queued request is holding a socket which (depending on OS) would be consuming a file handle. This is the kind of resource that the operating system will limit, so it may not be best to hold on to it unless needed. Therefore it also makes sense to bound the size of the work queue.</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="line"><span class="cl"><span class="kd">public</span><span class="w"> </span><span class="kd">static</span><span class="w"> </span><span class="n">ExecutorService</span><span class="w"> </span><span class="nf">newBoundedFixedThreadPool</span><span class="p">(</span><span class="kt">int</span><span class="w"> </span><span class="n">nThreads</span><span class="p">,</span><span class="w"> </span><span class="kt">int</span><span class="w"> </span><span class="n">capacity</span><span class="p">)</span><span class="w"> </span><span class="p">{</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">	</span><span class="k">return</span><span class="w"> </span><span class="k">new</span><span class="w"> </span><span class="n">ThreadPoolExecutor</span><span class="p">(</span><span class="n">nThreads</span><span class="p">,</span><span class="w"> </span><span class="n">nThreads</span><span class="p">,</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">		</span><span class="n">0L</span><span class="p">,</span><span class="w"> </span><span class="n">TimeUnit</span><span class="p">.</span><span class="na">MILLISECONDS</span><span class="p">,</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">		</span><span class="k">new</span><span class="w"> </span><span class="n">LinkedBlockingQueue</span><span class="o">&lt;</span><span class="n">Runnable</span><span class="o">&gt;</span><span class="p">(</span><span class="n">capacity</span><span class="p">),</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">		</span><span class="k">new</span><span class="w"> </span><span class="n">ThreadPoolExecutor</span><span class="p">.</span><span class="na">DiscardPolicy</span><span class="p">());</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="p">}</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="kd">public</span><span class="w"> </span><span class="kd">static</span><span class="w"> </span><span class="kt">void</span><span class="w"> </span><span class="nf">boundedThreadPoolServerSocket</span><span class="p">()</span><span class="w"> </span><span class="kd">throws</span><span class="w"> </span><span class="n">IOException</span><span class="w"> </span><span class="p">{</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">	</span><span class="n">ServerSocket</span><span class="w"> </span><span class="n">listener</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="k">new</span><span class="w"> </span><span class="n">ServerSocket</span><span class="p">(</span><span class="n">8080</span><span class="p">);</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">	</span><span class="n">ExecutorService</span><span class="w"> </span><span class="n">executor</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="n">newBoundedFixedThreadPool</span><span class="p">(</span><span class="n">4</span><span class="p">,</span><span class="w"> </span><span class="n">16</span><span class="p">);</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">	</span><span class="k">try</span><span class="w"> </span><span class="p">{</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">		</span><span class="k">while</span><span class="w"> </span><span class="p">(</span><span class="kc">true</span><span class="p">)</span><span class="w"> </span><span class="p">{</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">			</span><span class="n">Socket</span><span class="w"> </span><span class="n">socket</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="n">listener</span><span class="p">.</span><span class="na">accept</span><span class="p">();</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">			</span><span class="n">executor</span><span class="p">.</span><span class="na">submit</span><span class="p">(</span><span class="w"> </span><span class="k">new</span><span class="w"> </span><span class="n">HandleRequestRunnable</span><span class="p">(</span><span class="n">socket</span><span class="p">)</span><span class="w"> </span><span class="p">);</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">		</span><span class="p">}</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">	</span><span class="p">}</span><span class="w"> </span><span class="k">finally</span><span class="w"> </span><span class="p">{</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">		</span><span class="n">listener</span><span class="p">.</span><span class="na">close</span><span class="p">();</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">	</span><span class="p">}</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="p">}</span><span class="w">
</span></span></span></code></pre></div><p>Again, we create a thread pool, but instead of using the Executors.newFixedThreadPool helper method, we create the ThreadPoolExecutor ourselves, passing a bounded <a href="https://docs.oracle.com/javase/7/docs/api/java/util/concurrent/LinkedBlockingQueue.html">LinkedBlockingQueue</a> capped to 16 elements. Alternatively an <a href="https://docs.oracle.com/javase/7/docs/api/java/util/concurrent/ArrayBlockingQueue.html">ArrayBlockingQueue</a> could have be used, which is an implementation of a bounded buffer.</p>
<p>If all threads are busy, and the queue fills up, what happens next is defined by the last argument to the ThreadPoolExecutor. In this example, a <a href="https://docs.oracle.com/javase/7/docs/api/java/util/concurrent/ThreadPoolExecutor.DiscardPolicy.html">DiscardPolicy</a> is used, which simply discards any work that would overflow the queue. There are other policies, such as the <a href="https://docs.oracle.com/javase/7/docs/api/java/util/concurrent/ThreadPoolExecutor.AbortPolicy.html">AbortPolicy</a> which throws an exception, or the <a href="https://docs.oracle.com/javase/7/docs/api/java/util/concurrent/ThreadPoolExecutor.CallerRunsPolicy.html">CallerRunsPolicy</a> which executes the job on the caller’s thread. This CallerRunsPolicy provides a simple way to self limit the rate jobs can be added, however, it could be harmful, blocking a thread that should stay unblocked.</p>
<p>A good default policy is to Discard or Abort, which both drop the work. In these cases it would be easy to return a simple error to the client, such as a <a href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.5.4">HTTP 503 “Service unavailable”</a>. Some would argue that the queue size could just be increased, and then all work would eventually be run. However, users are unwilling to wait forever, and if fundamentally the rate at which work comes in, exceeds the rate it can be executed, then the queue will grow indefinitely. Instead the queue should only be used to smooth out bursts of requests, or handle short stalls in processing. In normal operation the queue should be empty.</p>
<h2 id="how-many-threads">How many threads?</h2>
<p>Now we understand how to create a thread pool, the hard question is how many threads should be available? We have determined that the maximum number should be bounded to not cause resource exhaustion. This includes all types of resources, memory (stack and heap), open file handles, open TCP connections, the number of connections a remote database can handle, and any other finite resource. Conversely, if the threads are CPU bound instead of IO bound, then the number of physical cores should be considered finite, and perhaps no more than one thread per core should be created.</p>
<p>This all depends on the work the application is doing. A user should run load tests using various pool sizes, and a realistic mix of requests. Each time increasing their thread pool size until breaking point. This makes it possible to find the upper bound, for when resources are exhausted. In some cases it may be prudent to increase the number of available resources, for example making more RAM available to the JVM, or tuning the OS to allow for more file handles. However, at some point the theoretical upper bound will be reached, and should be noted, but this is not the end of the story.</p>
<h2 id="littles-law">Little’s Law</h2>
<figure><img src="/post/2015/12/17/the-importance-of-tuning-your-thread-pools/littlelaw.png"><figcaption>
      <h4>Little&#39;s Law equation</h4>
    </figcaption>
</figure>

<p>Queuing theory, in particular, <a href="https://en.wikipedia.org/wiki/Little%27s_law">Little’s Law</a>, can be used to help understand the properties of the thread pool. In simple terms, Little’s Law describes the relationship between three variables; L the number of requests in-flight, λ the rate at which new requests arrive, and W the average time to handle the request. For example, if there are 10 requests arriving per second, and each request takes one second to process, there is an average of 10 request in-flight at any time. In our example, this maps to using 10 threads. If the time to process a single request is doubled, then the average in-flight requests also doubles to 20, and thus requires 20 threads.</p>
<p>Understanding the impact that execution time has on in-flight request is very important. It is common for some backend resource (such as a database) to stall, causing requests to take longer to process, quickly exhausting a thread pool. Therefore the theoretical upper bound may not be an appropriate limit for the pool size. Instead, a limit should be placed on execution time, and used in combination with the theoretical upper bound.</p>
<p>For example, let’s say the maximum in-flight requests that can be handled is 1000 before the JVM exceeds its memory allocation. If we budget for each request to take no longer than 30 seconds, we should expect in the worst case to handle no more than 33 ⅓ requests per second. However, if everything is working correctly, and requests take only 500ms to handle, the application can handle 2000 requests per second, on only 1000 threads. It may also be reasonable to specify that a queue can be used to smooth out short bursts of delay.</p>
<h2 id="why-the-hassle">Why the hassle?</h2>
<p>If the thread pool has too few threads, you run the risk of under utilising the resources, and turning users away unnecessarily. However, if too many threads are allowed, resource exhaustion occurs, which can be more damaging.</p>
<p>Not only can local resources be exhausted but it is possible to adversely impact others. Take for example, multiple applications querying the same backend database. Databases typically have a hard limit on the number of concurrent connections. If one misbehaving unbounded application consumes all these connections, it would block the others from accessing the database. Causing a widespread outage.</p>
<p>Even worse, a cascading failure could occur. Imagine an environment with multiple instances of a single application, behind a common load balancer. If one of the instances begins to run out of memory due to excessive in-flight requests, the JVM will spend more time garbage collecting, and less time handling the requests. That slow down, will reduce the capacity of that one instance, and force the other instances to handle a higher fraction of incoming requests. As they now handle more requests, with their unbounded thread pools, the same problem occurs. They run out of memory, and again begin aggressively garbage collecting. This vicious cycle cascades across all instances, until there is a systemic failure.</p>
<p>Far too often I’ve observed that load testing is not conducted, and an arbitrarily high number of threads is allowed. In the common case the application can happily process requests at the incoming rate using a small number of threads. If however, processing the requests depends on a remote service, and that service temporarily slows down, the impact of increasing W (the average processing time) can very quickly exhaust the pool. Because the application was never load tested at the maximum number, all the resource exhaustion issues outlined before are exhibited.</p>
<h2 id="how-many-thread-pools">How many thread pools?</h2>
<p>In <a href="http://martinfowler.com/articles/microservices.html">microservice</a>, or <a href="https://en.wikipedia.org/wiki/Service-oriented_architecture">service oriented architectures</a> (SOA), it is normal to access multiple remote backend services. This setup is particularly susceptible to failures, and thought should be given to gracefully dealing with them. If a remote service’s performance degrades, it can cause the thread pool to quickly hit its limit, and subsequent requests are dropped. However, not all requests may require this unhealthy backend, but since the thread pool is full these requests are needlessly dropped.</p>
<p>The failure of each backend can be isolated by providing backend specific thread pools. In this pattern, there is still a single request worker pool, but if the request needs to call a remote service, the work is transferred to that backend’s thread pool. This leaves the main request pool unburden by a single slow backend. Then only requests needing that particular backend pool are impacted when it malfunctions.</p>
<p>A final benefit of multiple thread pools, is it helps avoid a form of deadlock. If every available thread becomes blocked on a result of a yet to be processed request, then a deadlock occurs, and no thread is able to move forward. When using multiple pools, and having a good understanding of the work they execute, this issue can be somewhat mitigated.</p>
<h2 id="deadlines-and-other-best-practices">Deadlines and other best practices</h2>
<p>A common best practice is to ensure there is a deadline on all remote calls. That is, if the remote service does not respond within a reasonable time, the request is abandoned. The same technique can be used for work within the thread pool. Specifically, if the thread is processing one request for longer than a defined deadline, it should be terminated. Making room for a new request, and placing an upper bound on W.  This may seem like a waste, but if the user (which might typically be a web browser) is waiting for a response, then after 30 seconds the browser might just give up anyway, or more likely the user becomes impatient and navigates away.</p>
<p>Failing fast, is another approach that can be taken when creating pools for backends. If the backend has failed, the thread pool will quickly fill up with request waiting to connect to the unresponsive backend. Instead, the backend can be flagged as unhealthy, all subsequent requests could fail instantly instead of needlessly waiting. Note however, that a mechanism is needed to determine when the backend has become healthy again.</p>
<p>Finally, if a request will need to call multiple backends independently, it should be possible to call them in parallel, instead of sequentially. This would reduce the wait time, at the cost of increased threads.</p>
<p>Luckily, there is a great library, <a href="https://github.com/Netflix/Hystrix">hystrix</a>, which packages many of these best practices and exposes them in a simple and safe way.</p>
<h2 id="conclusion">Conclusion</h2>
<p>Hopefully this article has improved your understanding of thread pools.  By understanding the application’s needs, and using a combination of the maximum thread count, and the average response time, an appropriate thread pool can be determined. Not only will this avoid cascading failures, but help plan and provision your service.</p>
<p>Even though your application may not explicitly use a thread pool, they are implicitly used by your application server or higher level abstraction. <a href="https://tomcat.apache.org/tomcat-8.0-doc/config/http.html">Tomcat</a>, <a href="https://developer.jboss.org/wiki/ThreadPoolConfiguration">JBoss</a>, <a href="http://undertow.io/undertow-docs/undertow-docs-1.2.0/listeners.html">Undertow</a>, <a href="https://dropwizard.github.io/dropwizard/0.7.1/docs/manual/configuration.html">Dropwizard</a> all provides multiple tunables to their thread pools (the pool which your servlet is executed).</p>
</description>
    </item>
    
    <item>
      <title>Unrolling loops at runtime with Byte Buddy</title>
      <link>https://blog.bramp.net/post/2015/09/09/unrolling-loops-at-runtime-with-byte-buddy/</link>
      <pubDate>Wed, 09 Sep 2015 20:29:04 -0700</pubDate>
      
      <guid>https://blog.bramp.net/post/2015/09/09/unrolling-loops-at-runtime-with-byte-buddy/</guid>
      <description><p>While creating the <a href="https://blog.bramp.net/post/2015/08/26/unsafe-part-2-using-sun.misc.unsafe-to-create-a-contiguous-array-of-objects/"><code>UnsafeArrayList</code></a>, I encountered a problem that I felt I could optimise. The <a href="https://blog.bramp.net/post/2015/08/26/unsafe-part-2-using-sun.misc.unsafe-to-create-a-contiguous-array-of-objects/"><code>UnsafeArrayList</code></a> copies objects into off-heap memory, instead of what a normal <code>ArrayList</code> would do, which is to store references to the object in an array on the heap. For example an <code>UnsafeArrayList&lt;FourLong&gt;</code> holds instances of <a href="https://github.com/bramp/unsafe/blob/master/unsafe-tests/src/main/java/net/bramp/unsafe/examples/FourLongs.java">FourLongs</a>, whose fields consume a total of 32 bytes (4×8 bytes) of memory. By design, when <code>set()</code> or <code>get()</code> are called, the <a href="https://blog.bramp.net/post/2015/08/26/unsafe-part-2-using-sun.misc.unsafe-to-create-a-contiguous-array-of-objects/"><code>UnsafeArrayList</code></a> copies these 32 bytes into or out of a contiguous segment of memory.</p>
<p>To achieve the copying, <code>sun.misc.Unsafe</code>’s <a href="http://www.docjar.com/docs/api/sun/misc/Unsafe.html#putLong(long,+long)">putLong()</a> is repeatedly called, moving 8 bytes at a time. For example, this simple loop will copy a long’s worth of memory each iteration, from src, into dest:</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="line"><span class="cl"><span class="kd">final</span><span class="w"> </span><span class="kt">long</span><span class="w"> </span><span class="n">COPY_STRIDE</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="n">8</span><span class="p">;</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="kd">final</span><span class="w"> </span><span class="n">Unsafe</span><span class="w"> </span><span class="n">unsafe</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="n">UnsafeHelper</span><span class="p">.</span><span class="na">getUnsafe</span><span class="p">();</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="kd">public</span><span class="w"> </span><span class="kt">void</span><span class="w"> </span><span class="nf">copy</span><span class="p">(</span><span class="n">Object</span><span class="w"> </span><span class="n">dest</span><span class="p">,</span><span class="w"> </span><span class="kt">long</span><span class="w"> </span><span class="n">src</span><span class="p">)</span><span class="w"> </span><span class="p">{</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">	</span><span class="kt">long</span><span class="w"> </span><span class="n">destOffset</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="n">0</span><span class="p">;</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">	</span><span class="kt">long</span><span class="w"> </span><span class="n">destEnd</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="n">UnsafeHelper</span><span class="p">.</span><span class="na">sizeOf</span><span class="p">(</span><span class="n">dest</span><span class="p">);</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">	</span><span class="k">while</span><span class="w"> </span><span class="p">(</span><span class="n">destOffset</span><span class="w"> </span><span class="o">&lt;</span><span class="w"> </span><span class="n">dstEnd</span><span class="p">)</span><span class="w"> </span><span class="p">{</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">		</span><span class="n">unsafe</span><span class="p">.</span><span class="na">putLong</span><span class="p">(</span><span class="n">dest</span><span class="p">,</span><span class="w"> </span><span class="n">dstOffset</span><span class="p">,</span><span class="w"> </span><span class="n">unsafe</span><span class="p">.</span><span class="na">getLong</span><span class="p">(</span><span class="n">src</span><span class="p">));</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">		</span><span class="n">destOffset</span><span class="w"> </span><span class="o">+=</span><span class="w"> </span><span class="n">COPY_STRIDE</span><span class="p">;</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">		</span><span class="n">src</span><span class="w"> </span><span class="o">+=</span><span class="w"> </span><span class="n">COPY_STRIDE</span><span class="p">;</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">	</span><span class="p">}</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="p">}</span><span class="w">
</span></span></span></code></pre></div><p>Note, we use <code>putLong</code>, not because the <a href="https://blog.bramp.net/post/2015/08/26/unsafe-part-2-using-sun.misc.unsafe-to-create-a-contiguous-array-of-objects/"><code>UnsafeArrayList</code></a> is storing objects made up of longs, but because this is the <code>Unsafe</code> method that can copy the most in one go. This <code>putLong</code> method is thus being used as the building block to build a more complex looping copy method. Note, this works great for memory which is aligned on a 8 byte boundary, and the total copy is a multiple of 8 bytes. For the sake of this article, we make the assumption that this is always true.</p>
<p>In the <code>FourLong</code>&rsquo;s case, the copy method would iterates four times. This is predictable, and occurs every time we <code>get()</code> on a <code>UnsafeArrayList&lt;FourLong&gt;</code> instance. Since this copy loop will be executed every time <code>get()</code> is called, it is worth seeing if we can make it execute faster. A common optimisation is for the developer to manually <a href="https://en.wikipedia.org/wiki/Loop_unrolling">unroll the loop</a>, avoiding the loop counter, and producing potentially quicker code<sup id="fnref:1"><a href="#fn:1" class="footnote-ref" role="doc-noteref">1</a></sup>. In this case, manually unrolling the code is not possible because the parameterised type could be any size. For example, a <code>UnsafeArrayList&lt;Point&gt;</code> would only need to copy 8 bytes (two 4 byte ints). You would hope that the JIT would notice the loop always iterates the same number of times (for a particular list), and be able to remove the loop. Sadly, it does not seem to do this, perhaps because the JVM does not know what side effects <code>unsafe.{get,put}Long</code> have. To measure the cost of the looping we compare the previous code to this:</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="line"><span class="cl"><span class="kd">final</span><span class="w"> </span><span class="kt">int</span><span class="w"> </span><span class="n">COPY_STRIDE</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="n">8</span><span class="p">;</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="kd">final</span><span class="w"> </span><span class="n">Unsafe</span><span class="w"> </span><span class="n">unsafe</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="n">UnsafeHelper</span><span class="p">.</span><span class="na">getUnsafe</span><span class="p">();</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="kd">public</span><span class="w"> </span><span class="kt">void</span><span class="w"> </span><span class="nf">copy</span><span class="p">(</span><span class="n">Object</span><span class="w"> </span><span class="n">dest</span><span class="p">,</span><span class="w"> </span><span class="kt">long</span><span class="w"> </span><span class="n">src</span><span class="p">)</span><span class="w"> </span><span class="p">{</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">	</span><span class="k">assert</span><span class="p">(</span><span class="n">UnsafeHelper</span><span class="p">.</span><span class="na">sizeOf</span><span class="p">(</span><span class="n">dest</span><span class="p">)</span><span class="w"> </span><span class="o">==</span><span class="w"> </span><span class="n">4</span><span class="w"> </span><span class="o">*</span><span class="w"> </span><span class="n">COPY_STRIDE</span><span class="p">)</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">	</span><span class="kt">long</span><span class="w"> </span><span class="n">destOffset</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="n">0</span><span class="p">;</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">	</span><span class="n">unsafe</span><span class="p">.</span><span class="na">putLong</span><span class="p">(</span><span class="n">dest</span><span class="p">,</span><span class="w"> </span><span class="n">destOffset</span><span class="p">,</span><span class="w"> </span><span class="n">unsafe</span><span class="p">.</span><span class="na">getLong</span><span class="p">(</span><span class="n">src</span><span class="p">));</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">	</span><span class="n">destOffset</span><span class="w"> </span><span class="o">+=</span><span class="w"> </span><span class="n">COPY_STRIDE</span><span class="p">;</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">	</span><span class="n">src</span><span class="w"> </span><span class="o">+=</span><span class="w"> </span><span class="n">COPY_STRIDE</span><span class="p">;</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">	</span><span class="n">unsafe</span><span class="p">.</span><span class="na">putLong</span><span class="p">(</span><span class="n">dest</span><span class="p">,</span><span class="w"> </span><span class="n">destOffset</span><span class="p">,</span><span class="w"> </span><span class="n">unsafe</span><span class="p">.</span><span class="na">getLong</span><span class="p">(</span><span class="n">src</span><span class="p">));</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">	</span><span class="n">destOffset</span><span class="w"> </span><span class="o">+=</span><span class="w"> </span><span class="n">COPY_STRIDE</span><span class="p">;</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">	</span><span class="n">src</span><span class="w"> </span><span class="o">+=</span><span class="w"> </span><span class="n">COPY_STRIDE</span><span class="p">;</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">	</span><span class="n">unsafe</span><span class="p">.</span><span class="na">putLong</span><span class="p">(</span><span class="n">dest</span><span class="p">,</span><span class="w"> </span><span class="n">destOffset</span><span class="p">,</span><span class="w"> </span><span class="n">unsafe</span><span class="p">.</span><span class="na">getLong</span><span class="p">(</span><span class="n">src</span><span class="p">));</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">	</span><span class="n">destOffset</span><span class="w"> </span><span class="o">+=</span><span class="w"> </span><span class="n">COPY_STRIDE</span><span class="p">;</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">	</span><span class="n">src</span><span class="w"> </span><span class="o">+=</span><span class="w"> </span><span class="n">COPY_STRIDE</span><span class="p">;</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">	</span><span class="n">unsafe</span><span class="p">.</span><span class="na">putLong</span><span class="p">(</span><span class="n">dest</span><span class="p">,</span><span class="w"> </span><span class="n">destOffset</span><span class="p">,</span><span class="w"> </span><span class="n">unsafe</span><span class="p">.</span><span class="na">getLong</span><span class="p">(</span><span class="n">src</span><span class="p">));</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="p">}</span><span class="w">
</span></span></span></code></pre></div><p>When benchmarked, this manually unrolled code runs 2 times faster! This got me thinking, since a particular <a href="https://blog.bramp.net/post/2015/08/26/unsafe-part-2-using-sun.misc.unsafe-to-create-a-contiguous-array-of-objects/"><code>UnsafeArrayList</code></a> instance is always going to copy the same sized object, again and again and again, it could perhaps generate bytecode during creation, that unrolled the loop.</p>
<h2 id="enter-byte-buddy">Enter Byte Buddy</h2>
<p>Thus investigation into <a href="http://bytebuddy.net/">Byte Buddy</a> began, a library designed for generating bytecode at runtime. The rest of this article explains how to use Byte Buddy for this goal.</p>
<p>To start, I used Intellij IDEA’s “<a href="https://plugins.jetbrains.com/plugin/5918">Show Bytecode</a>” option, to inspect the code generated by my hand unrolled code.</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-nasm" data-lang="nasm"><span class="line"><span class="cl"><span class="c1">; Initialisation</span>
</span></span><span class="line"><span class="cl">  <span class="c1">; long destOffset = 0;</span>
</span></span><span class="line"><span class="cl">  <span class="nf">LCONST_0</span>  <span class="c1">; Load the long zero</span>
</span></span><span class="line"><span class="cl">  <span class="nf">LSTORE</span> <span class="mi">4</span>  <span class="c1">; Store it in “destOffset”</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl"><span class="c1">; Copy</span>
</span></span><span class="line"><span class="cl">  <span class="c1">; unsafe.putLong(dest, destOffset, unsafe.getLong(src));</span>
</span></span><span class="line"><span class="cl">  <span class="nf">ALOAD</span> <span class="mi">0</span>  <span class="c1">; Load “this”</span>
</span></span><span class="line"><span class="cl">  <span class="c1">; The the “unsafe” member from this.</span>
</span></span><span class="line"><span class="cl">  <span class="nf">GETFIELD</span> <span class="nv">net</span><span class="o">/</span><span class="nv">bramp</span><span class="o">/</span><span class="nv">unsafe</span><span class="o">/</span><span class="nv">Test.unsafe</span> <span class="p">:</span> <span class="nv">Lsun</span><span class="o">/</span><span class="nv">misc</span><span class="o">/</span><span class="nv">Unsafe</span><span class="c1">;</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">  <span class="nf">ALOAD</span> <span class="mi">1</span>  <span class="c1">; Load dest</span>
</span></span><span class="line"><span class="cl">  <span class="nf">LLOAD</span> <span class="mi">4</span>  <span class="c1">; Load dstOffset</span>
</span></span><span class="line"><span class="cl">  <span class="nf">ALOAD</span> <span class="mi">0</span>  <span class="c1">; Load this</span>
</span></span><span class="line"><span class="cl">  <span class="c1">; The the “unsafe” member from this.</span>
</span></span><span class="line"><span class="cl">  <span class="nf">GETFIELD</span> <span class="nv">net</span><span class="o">/</span><span class="nv">bramp</span><span class="o">/</span><span class="nv">unsafe</span><span class="o">/</span><span class="nv">Test.unsafe</span> <span class="p">:</span> <span class="nv">Lsun</span><span class="o">/</span><span class="nv">misc</span><span class="o">/</span><span class="nv">Unsafe</span><span class="c1">;</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">  <span class="nf">LLOAD</span> <span class="mi">2</span>  <span class="c1">; Load src</span>
</span></span><span class="line"><span class="cl">  <span class="c1">; unsafe.getLong(src), storing result on stack.</span>
</span></span><span class="line"><span class="cl">  <span class="nf">INVOKEVIRTUAL</span> <span class="nv">sun</span><span class="o">/</span><span class="nv">misc</span><span class="o">/</span><span class="nv">Unsafe.getLong</span> <span class="p">(</span><span class="nv">J</span><span class="p">)</span><span class="nv">J</span>
</span></span><span class="line"><span class="cl">  <span class="c1">; unsafe.putLong(dest, dstOffset, {stack result})</span>
</span></span><span class="line"><span class="cl">  <span class="nf">INVOKEVIRTUAL</span> <span class="nv">sun</span><span class="o">/</span><span class="nv">misc</span><span class="o">/</span><span class="nv">Unsafe.putLong</span> <span class="p">(</span><span class="nv">Ljava</span><span class="o">/</span><span class="nv">lang</span><span class="o">/</span><span class="nv">Object</span><span class="c1">;JJ)V</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl"><span class="c1">;; Increment</span>
</span></span><span class="line"><span class="cl">  <span class="c1">; dstOffset += 8;</span>
</span></span><span class="line"><span class="cl">  <span class="nf">LLOAD</span> <span class="mi">4</span>   <span class="c1">; Load dstOffset</span>
</span></span><span class="line"><span class="cl">  <span class="nf">LDC</span> <span class="mi">8</span>     <span class="c1">; Load 8</span>
</span></span><span class="line"><span class="cl">  <span class="nf">LADD</span>      <span class="c1">; Add dstOffset and 8</span>
</span></span><span class="line"><span class="cl">  <span class="nf">LSTORE</span> <span class="mi">4</span>  <span class="c1">; Store result to dstOffset</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">  <span class="c1">; src += 8;</span>
</span></span><span class="line"><span class="cl">  <span class="nf">LLOAD</span> <span class="mi">2</span>   <span class="c1">; Load src</span>
</span></span><span class="line"><span class="cl">  <span class="nf">LDC</span> <span class="mi">8</span>     <span class="c1">; Load 8</span>
</span></span><span class="line"><span class="cl">  <span class="nf">LADD</span>      <span class="c1">; Add src and 8</span>
</span></span><span class="line"><span class="cl">  <span class="nf">LSTORE</span> <span class="mi">2</span>  <span class="c1">; Store result to src</span>
</span></span></code></pre></div><p>After reading a <a href="http://download.forge.objectweb.org/asm/asm4-guide.pdf">primer to bytecode</a>, this generated bytecode looked quite simple. It can be broken up into three steps, initialisation, copy, and increment. At runtime, Byte Buddy can be used to generate bytecode that is an unrolled equivalent, such that there is 1 initialisation step, N copy steps, and N-1 increment steps, where N is based on the size of the object the <a href="https://blog.bramp.net/post/2015/08/26/unsafe-part-2-using-sun.misc.unsafe-to-create-a-contiguous-array-of-objects/"><code>UnsafeArrayList</code></a> plans to copy.</p>
<p>Reading through the Byte Buddy API it seems the best way to achieve this is to create an abstract class, which will form the base of a generated class. Then at runtime create an instantiation of this abstract class, specialised with the unrolled copy bytecode.</p>
<p>For example, the base class would look like this:</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="line"><span class="cl"><span class="kd">public</span><span class="w"> </span><span class="kd">abstract</span><span class="w"> </span><span class="kd">class</span> <span class="nc">UnsafeCopier</span><span class="w"> </span><span class="p">{</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">	</span><span class="kd">protected</span><span class="w"> </span><span class="kd">final</span><span class="w"> </span><span class="n">Unsafe</span><span class="w"> </span><span class="n">unsafe</span><span class="p">;</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">	</span><span class="kd">public</span><span class="w"> </span><span class="nf">UnsafeCopier</span><span class="p">(</span><span class="n">Unsafe</span><span class="w"> </span><span class="n">unsafe</span><span class="p">)</span><span class="w"> </span><span class="p">{</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">		</span><span class="k">this</span><span class="p">.</span><span class="na">unsafe</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="n">checkNotNull</span><span class="p">(</span><span class="n">unsafe</span><span class="p">);</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">	</span><span class="p">}</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">	</span><span class="kd">abstract</span><span class="w"> </span><span class="kt">void</span><span class="w"> </span><span class="nf">copy</span><span class="p">(</span><span class="n">Object</span><span class="w"> </span><span class="n">dest</span><span class="p">,</span><span class="w"> </span><span class="kt">long</span><span class="w"> </span><span class="n">src</span><span class="p">);</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="p">}</span><span class="w">
</span></span></span></code></pre></div><p>Leaving us to implement the <code>copy(…)</code> method optimally for the size of object being copied.</p>
<p>Using the <a href="https://en.wikipedia.org/wiki/Builder_pattern">Builder pattern</a> I created the <a href="https://bramp.github.io/unsafe/index.html?net/bramp/unsafe/UnrolledUnsafeCopierBuilder.html"><code>UnrolledUnsafeCopierBuilder</code></a> class. The <code>build()</code> method will calculate the size of the class being copied, then using Byte Buddy generate the copy implementation, and returns a specialised instance UnsafeCopier.</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="line"><span class="cl"><span class="kd">public</span><span class="w"> </span><span class="n">UnsafeCopier</span><span class="w"> </span><span class="nf">build</span><span class="p">(</span><span class="n">Unsafe</span><span class="w"> </span><span class="n">unsafe</span><span class="p">)</span><span class="w"> </span><span class="p">{</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">	</span><span class="kd">final</span><span class="w"> </span><span class="kt">long</span><span class="w"> </span><span class="n">length</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="n">UnsafeHelper</span><span class="p">.</span><span class="na">sizeOf</span><span class="p">(</span><span class="n">clazz</span><span class="p">);</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">	</span><span class="n">Class</span><span class="o">&lt;?&gt;</span><span class="w"> </span><span class="n">dynamicType</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="k">new</span><span class="w"> </span><span class="n">ByteBuddy</span><span class="p">()</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">		</span><span class="p">.</span><span class="na">subclass</span><span class="p">(</span><span class="n">UnsafeCopier</span><span class="p">.</span><span class="na">class</span><span class="p">)</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">		</span><span class="p">.</span><span class="na">method</span><span class="p">(</span><span class="n">named</span><span class="p">(</span><span class="s">&#34;copy&#34;</span><span class="p">))</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">		</span><span class="p">.</span><span class="na">intercept</span><span class="p">(</span><span class="k">new</span><span class="w"> </span><span class="n">CopierImplementation</span><span class="p">(</span><span class="n">length</span><span class="p">)).</span><span class="na">make</span><span class="p">()</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">		</span><span class="p">.</span><span class="na">load</span><span class="p">(</span><span class="n">getClass</span><span class="p">().</span><span class="na">getClassLoader</span><span class="p">(),</span><span class="w"> </span><span class="n">ClassLoadingStrategy</span><span class="p">.</span><span class="na">Default</span><span class="p">.</span><span class="na">WRAPPER</span><span class="p">)</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">		</span><span class="p">.</span><span class="na">getLoaded</span><span class="p">();</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">	</span><span class="k">return</span><span class="w"> </span><span class="p">(</span><span class="n">UnsafeCopier</span><span class="p">)</span><span class="w"> </span><span class="n">dynamicType</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">		</span><span class="p">.</span><span class="na">getDeclaredConstructor</span><span class="p">(</span><span class="n">Unsafe</span><span class="p">.</span><span class="na">class</span><span class="p">)</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">		</span><span class="p">.</span><span class="na">newInstance</span><span class="p">(</span><span class="n">unsafe</span><span class="p">);</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="p">}</span><span class="w">
</span></span></span></code></pre></div><p>This begins by calculating the size of the class. Then using a <a href="http://bytebuddy.net/javadoc/0.7-rc1/index.html?net/bytebuddy/ByteBuddy.html">ByteBuddy</a> instance, creates a new dynamicType, which extends <code>UnsafeCopier</code>. This subclass then obtains its copy method with code generated by <code>CopierImplementation(length)</code>. Finally, this new dynamicType is used to create an instance of the copier, which is now specialised for copying instances of clazz.</p>
<p>The real meat of the code is in <code>CopierImplementation</code>, which can be explained in pieces:</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="line"><span class="cl"><span class="kd">class</span> <span class="nc">CopierImplementation</span><span class="w"> </span><span class="kd">implements</span><span class="w"> </span><span class="n">ByteCodeAppender</span><span class="p">,</span><span class="w"> </span><span class="n">Implementation</span><span class="w"> </span><span class="p">{</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">	</span><span class="kd">public</span><span class="w"> </span><span class="kd">static</span><span class="w"> </span><span class="kd">final</span><span class="w"> </span><span class="kt">long</span><span class="w"> </span><span class="n">COPY_STRIDE</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="n">8</span><span class="p">;</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">	</span><span class="kd">final</span><span class="w"> </span><span class="kt">long</span><span class="w"> </span><span class="n">length</span><span class="p">;</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">	</span><span class="kd">public</span><span class="w"> </span><span class="nf">CopierImplementation</span><span class="p">(</span><span class="kt">long</span><span class="w"> </span><span class="n">length</span><span class="p">)</span><span class="w"> </span><span class="p">{</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">		</span><span class="k">this</span><span class="p">.</span><span class="na">length</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="n">length</span><span class="p">;</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">	</span><span class="p">}</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">	</span><span class="kd">private</span><span class="w"> </span><span class="n">StackManipulation</span><span class="w"> </span><span class="nf">buildStack</span><span class="p">()</span><span class="w"> </span><span class="kd">throws</span><span class="w"> </span><span class="p">...</span><span class="w"> </span><span class="p">{</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">		</span><span class="p">...</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">		</span><span class="kd">final</span><span class="w"> </span><span class="n">StackManipulation</span><span class="w"> </span><span class="n">setupStack</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="p">...</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">		</span><span class="kd">final</span><span class="w"> </span><span class="n">StackManipulation</span><span class="w"> </span><span class="n">copyStack</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="p">...</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">		</span><span class="kd">final</span><span class="w"> </span><span class="n">StackManipulation</span><span class="w"> </span><span class="n">incrementStack</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="p">...</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">		</span><span class="kd">final</span><span class="w"> </span><span class="kt">int</span><span class="w"> </span><span class="n">iterations</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="p">(</span><span class="kt">int</span><span class="p">)</span><span class="w"> </span><span class="p">(</span><span class="n">length</span><span class="w"> </span><span class="o">/</span><span class="w"> </span><span class="n">COPY_STRIDE</span><span class="p">);</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">		</span><span class="kd">final</span><span class="w"> </span><span class="n">StackManipulation</span><span class="o">[]</span><span class="w"> </span><span class="n">stack</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="k">new</span><span class="w"> </span><span class="n">StackManipulation</span><span class="o">[</span><span class="n">1</span><span class="w"> </span><span class="o">+</span><span class="w"> </span><span class="n">2</span><span class="w"> </span><span class="o">*</span><span class="w"> </span><span class="n">iterations</span><span class="o">]</span><span class="p">;</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">		
</span></span></span><span class="line"><span class="cl"><span class="w">		</span><span class="n">stack</span><span class="o">[</span><span class="n">0</span><span class="o">]</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="n">setupStack</span><span class="p">;</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">		</span><span class="k">for</span><span class="w"> </span><span class="p">(</span><span class="kt">int</span><span class="w"> </span><span class="n">i</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="n">0</span><span class="p">;</span><span class="w"> </span><span class="n">i</span><span class="w"> </span><span class="o">&lt;</span><span class="w"> </span><span class="n">iterations</span><span class="p">;</span><span class="w"> </span><span class="n">i</span><span class="o">++</span><span class="p">)</span><span class="w"> </span><span class="p">{</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">			</span><span class="n">stack</span><span class="o">[</span><span class="n">i</span><span class="w"> </span><span class="o">*</span><span class="w"> </span><span class="n">2</span><span class="w"> </span><span class="o">+</span><span class="w"> </span><span class="n">1</span><span class="o">]</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="n">copyStack</span><span class="p">;</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">			</span><span class="n">stack</span><span class="o">[</span><span class="n">i</span><span class="w"> </span><span class="o">*</span><span class="w"> </span><span class="n">2</span><span class="w"> </span><span class="o">+</span><span class="w"> </span><span class="n">2</span><span class="o">]</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="n">incrementStack</span><span class="p">;</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">		</span><span class="p">}</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">		</span><span class="c1">// Override the last incrementStack with a &#34;return&#34;</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">		</span><span class="n">stack</span><span class="o">[</span><span class="n">stack</span><span class="p">.</span><span class="na">length</span><span class="w"> </span><span class="o">-</span><span class="w"> </span><span class="n">1</span><span class="o">]</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="n">MethodReturn</span><span class="p">.</span><span class="na">VOID</span><span class="p">;</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">		</span><span class="k">return</span><span class="w"> </span><span class="k">new</span><span class="w"> </span><span class="n">StackManipulation</span><span class="p">.</span><span class="na">Compound</span><span class="p">(</span><span class="n">stack</span><span class="p">);</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">	</span><span class="p">}</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">	</span><span class="p">...</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="p">}</span><span class="w">
</span></span></span></code></pre></div><p>Byte Buddy uses <a href="http://bytebuddy.net/javadoc/0.7-rc1/net/bytebuddy/implementation/bytecode/StackManipulation.html"><code>StackManipulation</code></a> objects to define what bytecode to generate. These <a href="http://bytebuddy.net/javadoc/0.7-rc1/net/bytebuddy/implementation/bytecode/StackManipulation.html"><code>StackManipulation</code></a> objects can be built up hierarchically and contain all the bytecode instructions to execute. We define a separate <a href="http://bytebuddy.net/javadoc/0.7-rc1/net/bytebuddy/implementation/bytecode/StackManipulation.html"><code>StackManipulation</code></a> object for each step, and in the <code>buildStack()</code> method combine the steps multiple times into one array. In particular, this stack array contains one initialise step, N copy steps, and N-1 increment steps, with a <code>return</code> instruction on the end.</p>
<p>Recall from the early bytecode listing, that the initialisation was two bytecode operations, a LCONST, and LSTORE. In Byte Buddy, we can thus do the following:</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="line"><span class="cl"><span class="kd">final</span><span class="w"> </span><span class="n">StackManipulation</span><span class="w"> </span><span class="n">setupStack</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="k">new</span><span class="w"> </span><span class="n">StackManipulation</span><span class="p">.</span><span class="na">Compound</span><span class="p">(</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">	</span><span class="n">LongConstant</span><span class="p">.</span><span class="na">ZERO</span><span class="p">,</span><span class="w">                       </span><span class="c1">// LCONST_0</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">	</span><span class="n">MethodVariableStore</span><span class="p">.</span><span class="na">LONG</span><span class="p">.</span><span class="na">storeOffset</span><span class="o">[</span><span class="n">4</span><span class="o">]</span><span class="w">  </span><span class="c1">// LSTORE 4</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="p">);</span><span class="w">
</span></span></span></code></pre></div><p>Byte Buddy provides the primitives for most bytecode instructions, and can be built up in these <a href="http://bytebuddy.net/javadoc/0.7-rc1/net/bytebuddy/implementation/bytecode/StackManipulation.html"><code>StackManipulation</code></a> arrays. However, some instructions are missing, for example LADD (needed by the increment step). But it is simple enough to create one from scratch, as <a href="https://github.com/bramp/unsafe/tree/master/unsafe-unroller/src/main/java/net/bramp/unsafe/bytebuddy">shown  outside of this article</a>.</p>
<p>Next the copy step is defined which is a few more instructions than the increment, but relatively simple:</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="line"><span class="cl"><span class="kd">final</span><span class="w"> </span><span class="n">Field</span><span class="w"> </span><span class="n">unsafeField</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="n">UnsafeCopier</span><span class="p">.</span><span class="na">class</span><span class="p">.</span><span class="na">getDeclaredField</span><span class="p">(</span><span class="s">&#34;unsafe&#34;</span><span class="p">);</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="kd">final</span><span class="w"> </span><span class="n">Method</span><span class="w"> </span><span class="n">getLongMethod</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="n">Unsafe</span><span class="p">.</span><span class="na">class</span><span class="p">.</span><span class="na">getMethod</span><span class="p">(</span><span class="s">&#34;getLong&#34;</span><span class="p">,</span><span class="w"> </span><span class="kt">long</span><span class="p">.</span><span class="na">class</span><span class="p">);</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="kd">final</span><span class="w"> </span><span class="n">Method</span><span class="w"> </span><span class="n">putLongMethod</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="n">Unsafe</span><span class="p">.</span><span class="na">class</span><span class="p">.</span><span class="na">getMethod</span><span class="p">(</span><span class="s">&#34;putLong&#34;</span><span class="p">,</span><span class="n">Object</span><span class="p">.</span><span class="na">class</span><span class="p">,</span><span class="w"> </span><span class="kt">long</span><span class="p">.</span><span class="na">class</span><span class="p">,</span><span class="w"> </span><span class="kt">long</span><span class="p">.</span><span class="na">class</span><span class="p">);</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="kd">final</span><span class="w"> </span><span class="n">StackManipulation</span><span class="w"> </span><span class="n">copyStack</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="k">new</span><span class="w"> </span><span class="n">StackManipulation</span><span class="p">.</span><span class="na">Compound</span><span class="p">(</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">	</span><span class="c1">// unsafe.putLong(dest, destOffset, unsafe.getLong(src));</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">	</span><span class="n">MethodVariableAccess</span><span class="p">.</span><span class="na">REFERENCE</span><span class="p">.</span><span class="na">loadOffset</span><span class="o">[</span><span class="n">0</span><span class="o">]</span><span class="p">,</span><span class="w"> </span><span class="c1">// ALOAD 0 this</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">	</span><span class="n">FieldAccess</span><span class="p">.</span><span class="na">forField</span><span class="p">(</span><span class="k">new</span><span class="w"> </span><span class="n">FieldDescription</span><span class="p">.</span><span class="na">ForLoadedField</span><span class="p">(</span><span class="n">unsafeField</span><span class="p">))</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">	                                   </span><span class="p">.</span><span class="na">getter</span><span class="p">(),</span><span class="w"> </span><span class="c1">// GETFIELD</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">	</span><span class="n">MethodVariableAccess</span><span class="p">.</span><span class="na">REFERENCE</span><span class="p">.</span><span class="na">loadOffset</span><span class="o">[</span><span class="n">1</span><span class="o">]</span><span class="p">,</span><span class="w"> </span><span class="c1">// ALOAD 1 dest</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">	</span><span class="n">MethodVariableAccess</span><span class="p">.</span><span class="na">LONG</span><span class="p">.</span><span class="na">loadOffset</span><span class="o">[</span><span class="n">4</span><span class="o">]</span><span class="p">,</span><span class="w">      </span><span class="c1">// LLOAD 4 destOffset</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">	</span><span class="n">MethodVariableAccess</span><span class="p">.</span><span class="na">REFERENCE</span><span class="p">.</span><span class="na">loadOffset</span><span class="o">[</span><span class="n">0</span><span class="o">]</span><span class="p">,</span><span class="w"> </span><span class="c1">// ALOAD 0 this</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">	</span><span class="n">FieldAccess</span><span class="p">.</span><span class="na">forField</span><span class="p">(</span><span class="k">new</span><span class="w"> </span><span class="n">FieldDescription</span><span class="p">.</span><span class="na">ForLoadedField</span><span class="p">(</span><span class="n">unsafeField</span><span class="p">))</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">	                                   </span><span class="p">.</span><span class="na">getter</span><span class="p">(),</span><span class="w"> </span><span class="c1">// GETFIELD</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">	</span><span class="n">MethodVariableAccess</span><span class="p">.</span><span class="na">LONG</span><span class="p">.</span><span class="na">loadOffset</span><span class="o">[</span><span class="n">2</span><span class="o">]</span><span class="p">,</span><span class="w">      </span><span class="c1">// LLOAD 2 src</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">	</span><span class="n">MethodInvocation</span><span class="p">.</span><span class="na">invoke</span><span class="p">(</span><span class="k">new</span><span class="w"> </span><span class="n">MethodDescription</span><span class="p">.</span><span class="na">ForLoadedMethod</span><span class="p">(</span><span class="n">getLongMethod</span><span class="p">)),</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">	</span><span class="n">MethodInvocation</span><span class="p">.</span><span class="na">invoke</span><span class="p">(</span><span class="k">new</span><span class="w"> </span><span class="n">MethodDescription</span><span class="p">.</span><span class="na">ForLoadedMethod</span><span class="p">(</span><span class="n">putLongMethod</span><span class="p">))</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="p">);</span><span class="w">
</span></span></span></code></pre></div><p>Again, the bytecode instructions are created as a sequence of <a href="http://bytebuddy.net/javadoc/0.7-rc1/net/bytebuddy/implementation/bytecode/StackManipulation.html"><code>StackManipulation</code></a>, replicating the bytecode the java compiler code had generated earlier. This example contains a couple of new <a href="http://bytebuddy.net/javadoc/0.7-rc1/net/bytebuddy/implementation/bytecode/StackManipulation.html"><code>StackManipulation</code></a> classes, in particular the Field and Method Descriptions classes.</p>
<p>The final step is the increment step, which won’t be explained, but for the interested reader <a href="https://github.com/bramp/unsafe/blob/ff8f463bf60661ff63133e8a3beada7fd65c7c45/unsafe-unroller/src/main/java/net/bramp/unsafe/CopierImplementation.java#L86">the source can be found here</a>.</p>
<p>One last piece of information Byte Buddy needs, is the size of the stack needed for the <code>copy()</code> method, including any space local variables may need. The <a href="http://bytebuddy.net/javadoc/0.7-rc1/net/bytebuddy/implementation/bytecode/StackManipulation.html"><code>StackManipulation</code></a> comes in handy here, as it is able to infer some of these details from the byte code it represents. In particular, the following code calculates the stack size:</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="line"><span class="cl"><span class="kd">public</span><span class="w"> </span><span class="n">Size</span><span class="w"> </span><span class="nf">apply</span><span class="p">(</span><span class="n">MethodVisitor</span><span class="w"> </span><span class="n">methodVisitor</span><span class="p">,</span><span class="w"> </span><span class="n">Implementation</span><span class="p">.</span><span class="na">Context</span><span class="w"> </span><span class="n">implementationContext</span><span class="p">,</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">   </span><span class="n">MethodDescription</span><span class="w"> </span><span class="n">instrumentedMethod</span><span class="p">)</span><span class="w"> </span><span class="p">{</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">	</span><span class="p">...</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">	</span><span class="c1">// Call buildStack() (from above) to generate the bytecode</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">	</span><span class="n">StackManipulation</span><span class="w"> </span><span class="n">stack</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="n">buildStack</span><span class="p">();</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">	</span><span class="c1">// Calculate the size of this bytecode</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">	</span><span class="n">StackManipulation</span><span class="p">.</span><span class="na">Size</span><span class="w"> </span><span class="n">finalStackSize</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="n">stack</span><span class="p">.</span><span class="na">apply</span><span class="p">(</span><span class="n">methodVisitor</span><span class="p">,</span><span class="w"> </span><span class="n">implementationContext</span><span class="p">);</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">	</span><span class="c1">// Now return the size of this bytecode, plus two, which is the size of the local</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">	</span><span class="c1">// destOffset variable.</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">	</span><span class="k">return</span><span class="w"> </span><span class="k">new</span><span class="w"> </span><span class="n">Size</span><span class="p">(</span><span class="n">finalStackSize</span><span class="p">.</span><span class="na">getMaximalSize</span><span class="p">(),</span><span class="w"> </span><span class="n">instrumentedMethod</span><span class="p">.</span><span class="na">getStackSize</span><span class="p">()</span><span class="w"> </span><span class="o">+</span><span class="w"> </span><span class="n">2</span><span class="p">);</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="p">}</span><span class="w">
</span></span></span></code></pre></div><p>An important part here, is the <code>+2</code>, which makes room for the <code>long destOffset</code> variable. If that was missing, the generated bytecode would incorrectly write over instructions on the stack, and most likely crash the JVM.</p>
<p>Now at runtime the <a href="https://blog.bramp.net/post/2015/08/26/unsafe-part-2-using-sun.misc.unsafe-to-create-a-contiguous-array-of-objects/"><code>UnsafeArrayList</code></a>&rsquo;s constructor can use the <a href="https://bramp.github.io/unsafe/index.html?net/bramp/unsafe/UnrolledUnsafeCopierBuilder.html"><code>UnrolledUnsafeCopierBuilder</code></a> to generate a specialised <code>UnsafeCopier</code> designed for the exact class the <a href="https://blog.bramp.net/post/2015/08/26/unsafe-part-2-using-sun.misc.unsafe-to-create-a-contiguous-array-of-objects/"><code>UnsafeArrayList</code></a> is storing.</p>
<h2 id="results">Results</h2>
<p>Now we have most of what we need, it is worth benchmarking this code. Using <a href="http://openjdk.java.net/projects/code-tools/jmh/">JMH</a>, we can write three microbenchmarks. One using the original looping code, one using the hand unrolled code, and one using the Byte Buddy unrolled code. The <a href="https://github.com/bramp/unsafe/blob/master/unsafe-benchmark/src/main/java/net/bramp/unsafe/copier/UnrolledCopierBenchmark.java">code for the benchmarks</a> is on GitHub, and follows a similar methodology to that in a <a href="https://blog.bramp.net/post/2015/08/27/unsafe-part-3-benchmarking-a-java-unsafearraylist/">previous article</a>.</p>
<p>The results are as you may expect:</p>















<table class="table">
  <thead>
      <tr>
          <th>Benchmark</th>
          <th>Mode</th>
          <th>Cnt</th>
          <th>Score</th>
          <th>Error</th>
          <th>Units</th>
      </tr>
  </thead>
  <tbody>
      <tr>
          <td>Loop</td>
          <td>thrpt</td>
          <td>25</td>
          <td>218.056</td>
          <td>± 11.123</td>
          <td>ops/us</td>
      </tr>
      <tr>
          <td>Hand Unrolled</td>
          <td>thrpt</td>
          <td>25</td>
          <td>430.376</td>
          <td>± 27.448</td>
          <td>ops/us</td>
      </tr>
      <tr>
          <td>Byte Buddy Unrolled</td>
          <td>thrpt</td>
          <td>25</td>
          <td>437.139</td>
          <td>± 22.811</td>
          <td>ops/us</td>
      </tr>
  </tbody>
</table>

<p>The loop code can execute ~218 times per microseconds, whereas both the Byte Buddy, and hand unrolled code had near identical performance, of ~430-437 iterations per microsecond, nearly twice as fast. Of course, not measured here is the startup cost of generating the unrolled code. It is assumed this technique would only be used when the generated code would exist for a long time. Otherwise the setup cost undoes any per execution savings.</p>
<h2 id="conclusion">Conclusion</h2>
<p>In summary, we managed to unroll a loop at runtime by generating on demand bytecode for that specific purpose. This was possible by inspecting machine generated bytecode, and using Byte Buddy to generate equivalent bytecode at runtime, customised specifically with the correct number of unrolled iterations.</p>
<p>This technique may seem completely crazy, and I don’t suggest its used unless you know what you are doing. That includes, actually measuring you have a performance problem which could be fixed with this, and not being able to depend on the JVM’s own JIT to do this optimisation for you.</p>
<p><em>Helpful Links:</em> <a href="https://github.com/bramp/unsafe/">GitHub Home</a> | <a href="https://github.com/bramp/unsafe/tree/master/unsafe-unroller/src/main/java/net/bramp/unsafe">Gitub Code</a> | <a href="https://bramp.github.io/unsafe/">JavaDoc</a></p>
<div class="footnotes" role="doc-endnotes">
<hr>
<ol>
<li id="fn:1">
<p>Unrolled code is not always faster, as larger code may not fit into CPU instruction cache.&#160;<a href="#fnref:1" class="footnote-backref" role="doc-backlink">&#x21a9;&#xfe0e;</a></p>
</li>
</ol>
</div>
</description>
    </item>
    
    <item>
      <title>Unsafe Part 3: Benchmarking a java UnsafeArrayList</title>
      <link>https://blog.bramp.net/post/2015/08/27/unsafe-part-3-benchmarking-a-java-unsafearraylist/</link>
      <pubDate>Thu, 27 Aug 2015 20:39:04 -0700</pubDate>
      
      <guid>https://blog.bramp.net/post/2015/08/27/unsafe-part-3-benchmarking-a-java-unsafearraylist/</guid>
      <description><p>Previously we introduced a <a href="https://blog.bramp.net/post/2015/08/26/unsafe-part-2-using-sun.misc.unsafe-to-create-a-contiguous-array-of-objects/">UnsafeArrayList</a>, an ArrayList style collection that instead of storing references to the objects, it would use <a href="http://www.docjar.com/docs/api/sun/misc/Unsafe.html">sun.misc.Unsafe</a> and <a href="https://blog.bramp.net/post/2015/08/24/unsafe-part-1-sun.misc.unsafe-helper-classes/">UnsafeHelper</a> to copy the objects into heap allocated memory. This has the unique property of keeping all objects contiguous in memory, and avoids a pointer indirection, at the cost of needing to copy values in and out. This article aims to benchmark this list, and understand its unique characteristics.</p>
<h2 id="methodology">Methodology</h2>
<p>To test the performance of this new style of list, a series of benchmarks were devised. The new <a href="http://openjdk.java.net/projects/code-tools/jmh/">JMH benchmark framework</a> was used, and final benchmark code is <a href="https://github.com/bramp/unsafe/tree/master/unsafe-benchmark">available here</a>.</p>
<p>Multiple iterations were run, and unless stated results were calculated with a 99% confidence interval. A couple of warmup iteration were always run and discarded. All tests were run on a Ubuntu Linux 3.19.0-22 desktop, with a 64bit Intel® Core™ i3-2125 CPU @ 3.30GHz, and 16 GiB of 1333 MHz DDR3 RAM. The JVM was OpenJDK (version 1.8.0_45-internal).</p>
<p>For each benchmark new ArrayLists and UnsafeArrayLists were constructed, and populated with newly created objects. The size of the lists were varied, up to a maximum that could be held in memory without disk swapping. Two artificial workloads were created,</p>
<ol>
<li>Reading items from the lists start to finish, and</li>
<li>Processing the elements in a random order.</li>
</ol>
<p>The first was reproduced by simply reading the first field of every element of the list in order, and the second by sorting the list based on the object’s fields (with a simple quicksort).</p>
<p>Three test classes of different sizes were created to be stored within the ArrayLists, one class had two long fields, one had four long fields, and finally one with eight long fields . Named TwoLongs, FourLongs and EightLongs requiring 16, 32, and 64 bytes for the fields respectively. Each iteration these classes were created with random values in the fields.</p>
<h2 id="the-results">The Results</h2>
<table class="table table-hover table-striped table-condensed">
	<thead>
		<tr><th>Benchmark</th><th>List</th><th>Type</th><th>Size</th><th class="text-center">Mean Time (s)</th></tr>
	</thead>
	<tbody>
		<tr><td>Iterate</td><td>ArrayList</td><td>TwoLongs</td><td>80,000,000</td><td class="text-center">2.266 ± 0.229</td></tr>
		<tr><td>Iterate</td><td>UnsafeArrayList</td><td>TwoLongs</td><td>80,000,000</td><td class="text-center">1.79 ± 0.03</td></tr>
		<tr><td>IterateInPlace</td><td>UnsafeArrayList</td><td>TwoLongs</td><td>80,000,000</td><td class="text-center">0.442 ± 0.023</td></tr>
		<tr><td></td><td></td><td></td><td></td><td></td></tr>
		<tr><td>Iterate</td><td>ArrayList</td><td>FourLongs</td><td>80,000,000</td><td class="text-center">2.277 ± 0.211</td></tr>
		<tr><td>Iterate</td><td>UnsafeArrayList</td><td>FourLongs</td><td>80,000,000</td><td class="text-center">2.126 ± 0.019</td></tr>
		<tr><td>IterateInPlace</td><td>UnsafeArrayList</td><td>FourLongs</td><td>80,000,000</td><td class="text-center">0.648 ± 0.019</td></tr>
		<tr><td></td><td></td><td></td><td></td><td></td></tr>
		<tr><td>Iterate</td><td>ArrayList</td><td>EightLongs</td><td>80,000,000</td><td class="text-center">2.792 ± 0.072</td></tr>
		<tr><td>Iterate</td><td>UnsafeArrayList</td><td>EightLongs</td><td>80,000,000</td><td class="text-center">2.672 ± 0.322</td></tr>
		<tr><td>IterateInPlace</td><td>UnsafeArrayList</td><td>EightLongs</td><td>80,000,000</td><td class="text-center">0.941 ± 0.032</td></tr>
		<tr><td></td><td></td><td></td><td></td><td></td></tr>
		<tr><td>Sort</td><td>ArrayList</td><td>TwoLongs</td><td>80,000,000</td><td class="text-center">70.31 ± 3.939</td></tr>
		<tr><td>Sort</td><td>ArrayList</td><td>FourLongs</td><td>80,000,000</td><td class="text-center">79.673 ± 6.119</td></tr>
		<tr><td>Sort</td><td>ArrayList</td><td>EightLongs</td><td>80,000,000</td><td class="text-center">97.687 ± 4.86</td></tr>
		<tr><td></td><td></td><td></td><td></td><td></td></tr>
		<tr><td>Sort</td><td>UnsafeArrayList</td><td>TwoLongs</td><td>80,000,000</td><td class="text-center">18.69 ± 3.158</td></tr>
		<tr><td>Sort</td><td>UnsafeArrayList</td><td>FourLongs</td><td>80,000,000</td><td class="text-center">24.822 ± 0.79</td></tr>
		<tr><td>Sort</td><td>UnsafeArrayList</td><td>EightLongs</td><td>80,000,000</td><td class="text-center">40.697 ± 0.743</td></tr>
	</tbody>
</table>
<h3 id="iterate">Iterate</h3>
<p>Starting with the smallest test object, TwoLongs, to read the first field of all 80 million  elements within an ArrayList took on average 2.266 ± 0.229 seconds. To do the same with the UnsafeArrayList (which doesn’t store objects, and instead copies elements in/out) took on average 1.79 ±0.03 seconds (an 24% improvement).</p>
<p>Remember in the <a href="https://blog.bramp.net/post/2015/08/26/unsafe-part-2-using-sun.misc.unsafe-to-create-a-contiguous-array-of-objects/">previous article</a>, UnsafeArrayList has two methods for retrieving an element <code>T get(int index)</code> and a <code>T get(T dest, int index)</code>. The former creates a new object and copies the fields. The latter copies the fields in place of a given destination object, allowing the reuse of a single temp object, and avoiding creations of new objects, thus is labelled &ldquo;InPlace&rdquo; in the above results.</p>
<p>It is therefore surprising that the UnsafeArrayList can iterate 24% faster than an ArrayList, when it has the additional overhead of creating an object, and copying fields into it. Compared to an ArrayList which is just reading existing objects.</p>
<p>Some theory is needed to understand what might be happening here. A modern CISC CPU can execute an instruction in a few clock cycles, let&rsquo;s say ~0.5 nanoseconds, however, reading from RAM takes ~10 nanoseconds. While the CPU is waiting for the response from RAM it is effectively blocked. To compensate the CPU deploys a few tricks, two of which could be helping here. Firstly, the CPU tries to predicting and prefetch the next memory request. Secondly, the CPU will execute instructions out of order, thus not waiting for the memory if a later instruction does not depend on the read.</p>
<p>In the ArrayList case, the array of reference is stored in contiguous memory. However, the actual objects (that the references point to) could be anywhere in RAM. As the program loops through it is making reads from effectively random locations in memory, that can’t be predicted, and thus stalls the CPU.</p>
<p>There is no doubt in the UnsafeArrayList the CPU is prefetching the next elements before it is needed. Additionally the cost of creating these short lived objects is most likely very small because they live and die in eden space and are thus simple to create and garbage collect. I also would not be surprised if the CPU or the JIT compiler was able to do <a href="https://en.wikipedia.org/wiki/Automatic_vectorization">some kind of vectorising</a> on the input. That is, concurrently operating on multiple entries at the same time.</p>
<p>If we then test the <code>T get(T dest, int index)</code> method (labelled IterateInPlace), it can iterate through the array in an impressive 0.442 ±0.023 seconds. That’s 5 times faster than the ArrayList, and 4 times faster than the <code>T get(int index)</code>. This is certainly because the objects are not created for each get.</p>
<p>It was not measured here, but it is possible to confirm what the CPU is doing, by using <a href="https://en.wikipedia.org/wiki/Hardware_performance_counter">hardware based performance counters</a>. These are special registers within the CPU that can be configured to measure cache hit/miss rates, prefetches, instructions per cycle, and many other metrics. These can be invaluable to understand what’s truly going on, as in most cases humans are bad at understanding performance bottlenecks through intuition alone. Tools such as <a href="http://oprofile.sourceforge.net/">oprofile</a>, <a href="https://perf.wiki.kernel.org/index.php/Main_Page">perf</a>, <a href="https://en.wikipedia.org/wiki/DTrace">dtrace</a> and <a href="https://sourceware.org/systemtap/">systemtap</a> can be used for this.</p>
<p>To do a quick sanity check, in the ArrayList case it takes an average of 28.325 nanoseconds per element. <a href="https://en.wikipedia.org/wiki/CAS_latency">According to wikipedia</a> it takes between 9.00-18.75 nanoseconds to read from DDR3 memory at 1333 Mhz. Thus this number doesn’t seem unexpected, as the ArrayList has to issue two memory reads, firstly reading sequentially from an array of references, and then reading from the object (which is at an unpredictable address).</p>
<p>With the UnsafeArrayList in-place test, it takes an average of 5.53 nanoseconds per element. As the fields are stored contiguously in memory, the CPU can efficiency pipeline the requests, amortizing the 9-18 ns memory read cost. Here the speed is most likely limited by either the memory’s bandwidth, or the CPU’s clock cycles.  To read 80 million memory addresses in 0.442 seconds, requires 180 Megatransfers per second, and assuming each object is two longs, or 16 bytes requires ~2.68 GiB/s of throughput. Neither of those values approach the upper limit of what DDR3 is capable of, thus I suspect the time is a combination of this and CPU instructions.</p>
<h3 id="sorting">Sorting</h3>
<p>The second benchmark measured the speed at which the lists could be read and written to somewhat randomly, and in particular sorted. This should cause a less predictable reads from memory.  To sort 80 million elements in the ArrayList took 70.31 ±3.939 seconds, and only 18.69 ±3.158 seconds for the UnsafeArrayList using the in-place get. The relative times is not as impressive as the previous test, but still the UnsafeArrayList is ~3.7 times as quick.  I’m unsure exactly why the UnsafeArrayList would be faster, but I suspect it is related to the fewer memory indirections, and prefetching effect the copying of fields has.</p>
<p>It’s also worth noting, the increase performance becomes less profound as the size of the stored class increases. For the FourLong the difference between ArrayList and UnsafeArrayList is 3.2x, and for EightLong the difference is 2.4x. This can easily be explained by the increasing cost of copying the fields in and out of the list. Even so, I would argue that the copy cost is in part hidden, as it is effectively prefetching the object’s fields into the CPU cache. Saving a memory load when the field is actually used (most likely shortly after it is pulled from the list).</p>
<h3 id="other-observations">Other observations</h3>
<p>Overlooked is the smaller memory requirements for the UnsafeArrayList. A TwoLong instance is 16 bytes of data, plus 16 bytes of JVM object header. Thus an ArrayList of 40 million instances take 2.4 GiB of RAM (32 bytes x 80M), plus an additional 305MiB for an array of 80 million references (assuming <a href="https://docs.oracle.com/javase/7/docs/technotes/guides/vm/performance-enhancements-7.html#compressedOop">compressed object pointers</a> takes 4 bytes each). Totalling 2.68 GiB, whereas the UnsafeArray takes 16 bytes per entry, totaling only 1.2GiB (roughly half the size!).</p>
<p>Of course if the array is holding larger classes (such as the EightLong), the per object overhead is smaller, in these cases 6.25GiB vs 4.76GiB, roughly 75% the size.</p>
<p>One last observation of interest is the confidence intervals for the results. A larger error implies more variability in the test runs. For example, if the garbage collector ran during some of the runs, and slowed down the test, it would increase this error. In all the tests using the UnsafeArrayList in-place methods, the confidence interval is smaller, implying more constancy and predictability. This can be important in certain situations, such as real-time systems.</p>
<h2 id="conclusion">Conclusion</h2>
<p>We benchmarked the <a href="https://bramp.github.io/unsafe/index.html?net/bramp/unsafe/UnsafeHelper.html">UnsafeArrayList</a>, against a normal ArrayList in two artificial workloads. We found that in both the start-to-finish iteration, and in the sorting case, that the UnsafeArrayList was 4-5x faster than its counterpart. This result itself is interesting when designing high performance data structures, however, the use of <a href="http://www.docjar.com/docs/api/sun/misc/Unsafe.html">sun.misc.Unsafe</a> is considered dangerous, and thus the performance comes with many caveats and risks. In fact, it was recently announced that the <a href="http://blog.dripstat.com/removal-of-sun-misc-unsafe-a-disaster-in-the-making/">Unsafe class is being deprecated and hidden in java 9</a>. So instead, this was just an insightful journey into how the CPU can optomise particular workloads, and how Java can be pushed to extreme speeds.</p>
<p>Your results may vary, and as always you should benchmark your exact workload instead of a hypothetical one, but this was still an interesting experiment.</p>
</description>
    </item>
    
    <item>
      <title>Unsafe Part 2: Using sun.misc.Unsafe to create a contiguous array of objects</title>
      <link>https://blog.bramp.net/post/2015/08/26/unsafe-part-2-using-sun.misc.unsafe-to-create-a-contiguous-array-of-objects/</link>
      <pubDate>Wed, 26 Aug 2015 17:51:02 -0700</pubDate>
      
      <guid>https://blog.bramp.net/post/2015/08/26/unsafe-part-2-using-sun.misc.unsafe-to-create-a-contiguous-array-of-objects/</guid>
      <description><p>I recently came across an article from the <a href="http://mechanical-sympathy.blogspot.com/2012/10/compact-off-heap-structurestuples-in.html">Mechanical Sympathy blog</a>, that used the <a href="https://en.wikipedia.org/wiki/Flyweight_pattern">flyweight pattern</a> to build a “compact off-heap” array of objects. They basically allocated an area of memory large enough to store N copies of their object. Then using a single instance of a proxy object, would pack/unpack fields into this memory. For example, let&rsquo;s say we needed to store an array of <a href="https://docs.oracle.com/javase/7/docs/api/java/awt/Point.html">Point</a> objects. We could construct a simple array like so:</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="line"><span class="cl"><span class="n">Point</span><span class="o">[]</span><span class="w"> </span><span class="n">points</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="k">new</span><span class="w"> </span><span class="n">Point</span><span class="o">[</span><span class="n">N</span><span class="o">]</span><span class="p">;</span><span class="w">
</span></span></span></code></pre></div><p>The inefficiency here is that each instance of a Point requires 12-16 bytes of overhead to store metadata about the object (such as class, GC state, etc), and each additional instance adds to the cost of garbage collection. Additionally, the array actually contains references to Point objects stored elsewhere in RAM. These references require a memory indirection when accessing the actual instances.</p>
<p>In the <a href="http://mechanical-sympathy.blogspot.com/2012/10/compact-off-heap-structurestuples-in.html">Mechanical Sympathy</a> article, they instead packed all the fields of the instances into a contiguous array. For simplification I changed their example, but it was something like this:</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="line"><span class="cl"><span class="kt">int</span><span class="o">[]</span><span class="w"> </span><span class="n">memory</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="k">new</span><span class="w"> </span><span class="kt">int</span><span class="o">[</span><span class="n">N</span><span class="o">*</span><span class="n">2</span><span class="o">]</span><span class="p">;</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="kd">class</span> <span class="nc">ProxyPoint</span><span class="w"> </span><span class="p">{</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">    </span><span class="kd">private</span><span class="w"> </span><span class="kt">int</span><span class="w"> </span><span class="n">index</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="n">0</span><span class="p">;</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">    </span><span class="kd">public</span><span class="w"> </span><span class="kt">void</span><span class="w"> </span><span class="nf">setIndex</span><span class="p">(</span><span class="kt">int</span><span class="w"> </span><span class="n">index</span><span class="p">)</span><span class="w"> </span><span class="p">{</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">        </span><span class="k">this</span><span class="p">.</span><span class="na">index</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="n">index</span><span class="p">;</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">    </span><span class="p">}</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">    </span><span class="kd">public</span><span class="w"> </span><span class="kt">int</span><span class="w"> </span><span class="nf">getX</span><span class="p">()</span><span class="w"> </span><span class="p">{</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">    	</span><span class="k">return</span><span class="w"> </span><span class="n">memory</span><span class="o">[</span><span class="n">index</span><span class="o">*</span><span class="n">2</span><span class="w"> </span><span class="o">+</span><span class="w"> </span><span class="n">0</span><span class="o">]</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">    </span><span class="p">}</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">    </span><span class="kd">public</span><span class="w"> </span><span class="kt">int</span><span class="w"> </span><span class="nf">getY</span><span class="p">()</span><span class="w"> </span><span class="p">{</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">    	</span><span class="k">return</span><span class="w"> </span><span class="n">memory</span><span class="o">[</span><span class="n">index</span><span class="o">*</span><span class="n">2</span><span class="w"> </span><span class="o">+</span><span class="w"> </span><span class="n">1</span><span class="o">]</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">    </span><span class="p">}</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="p">}</span><span class="w">
</span></span></span></code></pre></div><p>With this approach there is no overhead for each Point object (as there is only ever one PointProxy, and one array). This also has the interesting property that the fields for all the Points are stored in the same contiguous region of memory.  Which leads to some great cache/CPU benefits. For example, if you read all the points sequentially, adjacent objects share the same CPU cache line, and the CPU can predictably prefetch the next point. This would not be possible with an array of references to Points, as each Point could potentially be stored anywhere in RAM.</p>
<p>Now with this primer, it would be interesting to have a normal Java <a href="https://docs.oracle.com/javase/8/docs/api/java/util/List.html">List</a> that stored fields packed together like this. The above solution only works if you create a proxy object ahead of time knowing what class you would be storing. Using the recently released <a href="https://bramp.github.io/unsafe/index.html?net/bramp/unsafe/UnsafeHelper.html">UnsafeHelper class</a> (<a href="https://blog.bramp.net/post/2015/08/24/unsafe-part-1-sun.misc.unsafe-helper-classes/">discussed previously</a>), I went about to build something that looked like a standard generic ArrayList, that could store any type. But with the benefit of storing all elements in contiguous region of memory.</p>
<p>The final solution is <a href="https://bramp.github.io/unsafe/index.html?net/bramp/unsafe/UnsafeArrayList.html">UnsafeArrayList.java</a>. This implements the Java List interface, but instead of storing references to objects, it copies the object into a contiguous region of memory. If you are a C++ programmer, you can think of this as a <code>std::vector&lt;Point&gt;</code> instead of a <code>std::vector&lt;Point*&gt;</code>. This minor change comes with it’s own pros and cons, outlined later.</p>
<p>To begin with the list is constructed like so <code>new UnsafeArrayList&lt;Point&gt;(Point.class)</code>. The <code>Point.class</code> is passed in so that the list knows what kind of objects it will be storing. This is required due to a limitation in Java’s implementation of generics, that makes it <a href="http://stackoverflow.com/q/182636/88646">impossible for a class to know its own generic type</a>.</p>
<p>The constructor begins by calculating the size of an instance, and uses the UnsafeHelper to calculates the offset to the first field within an instance.</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="line"><span class="cl"><span class="kd">public</span><span class="w"> </span><span class="nf">UnsafeArrayList</span><span class="p">(</span><span class="n">Class</span><span class="o">&lt;</span><span class="n">T</span><span class="o">&gt;</span><span class="w"> </span><span class="n">type</span><span class="p">,</span><span class="w"> </span><span class="kt">int</span><span class="w"> </span><span class="n">capacity</span><span class="p">)</span><span class="w"> </span><span class="p">{</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">    </span><span class="k">this</span><span class="p">.</span><span class="na">firstFieldOffset</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="n">UnsafeHelper</span><span class="p">.</span><span class="na">firstFieldOffset</span><span class="p">(</span><span class="n">type</span><span class="p">);</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">    </span><span class="k">this</span><span class="p">.</span><span class="na">elementSize</span><span class="w">      </span><span class="o">=</span><span class="w"> </span><span class="n">UnsafeHelper</span><span class="p">.</span><span class="na">sizeOf</span><span class="p">(</span><span class="n">type</span><span class="p">)</span><span class="w"> </span><span class="o">-</span><span class="w"> </span><span class="n">firstFieldOffset</span><span class="p">;</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">    </span><span class="k">this</span><span class="p">.</span><span class="na">unsafe</span><span class="w">           </span><span class="o">=</span><span class="w"> </span><span class="n">UnsafeHelper</span><span class="p">.</span><span class="na">getUnsafe</span><span class="p">();</span><span class="w">
</span></span></span></code></pre></div><p>An area of memory is then allocated, like so:</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="line"><span class="cl"><span class="w">    </span><span class="n">base</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="n">unsafe</span><span class="p">.</span><span class="na">allocateMemory</span><span class="p">(</span><span class="n">elementSize</span><span class="w"> </span><span class="o">*</span><span class="w"> </span><span class="n">capacity</span><span class="p">);</span><span class="w">
</span></span></span></code></pre></div><p>This base variable holds the address to the beginning of the memory, and can only be used via the Unsafe class. The memory is large enough to hold <code>capacity</code> objects of <code>elementSize</code> bytes.</p>
<p>Unlike a Java reference, this base address allows <a href="https://www.cs.umd.edu/class/sum2003/cmsc311/Notes/BitOp/pointer.html">pointer arithmetic</a>, and thus to access a particular element we have a simple method to calculate the memory offset:</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="line"><span class="cl"><span class="w">    </span><span class="kd">private</span><span class="w"> </span><span class="kt">long</span><span class="w"> </span><span class="nf">offset</span><span class="p">(</span><span class="kt">int</span><span class="w"> </span><span class="n">index</span><span class="p">)</span><span class="w"> </span><span class="p">{</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">        </span><span class="k">return</span><span class="w"> </span><span class="n">base</span><span class="w"> </span><span class="o">+</span><span class="w"> </span><span class="p">(</span><span class="n">index</span><span class="w"> </span><span class="o">*</span><span class="w"> </span><span class="n">elementSize</span><span class="p">);</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">    </span><span class="p">}</span><span class="w">
</span></span></span></code></pre></div><p>Then to <a href="https://bramp.github.io/unsafe/net/bramp/unsafe/UnsafeArrayList.html#set-int-T-">set</a> an element within this List, we copy its fields into the allocated memory:</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="line"><span class="cl"><span class="w">    </span><span class="nd">@Override</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">    </span><span class="kd">public</span><span class="w"> </span><span class="n">T</span><span class="w"> </span><span class="nf">set</span><span class="p">(</span><span class="kt">int</span><span class="w"> </span><span class="n">index</span><span class="p">,</span><span class="w"> </span><span class="n">T</span><span class="w"> </span><span class="n">element</span><span class="p">)</span><span class="w"> </span><span class="p">{</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">        </span><span class="n">unsafe</span><span class="p">.</span><span class="na">copyMemory</span><span class="p">(</span><span class="n">element</span><span class="p">,</span><span class="w"> </span><span class="n">firstFieldOffset</span><span class="p">,</span><span class="w"> </span><span class="c1">// src, src_offset</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">                          </span><span class="kc">null</span><span class="p">,</span><span class="w"> </span><span class="n">offset</span><span class="p">(</span><span class="n">index</span><span class="p">),</span><span class="w">       </span><span class="c1">// dst, dst_offset</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">                          </span><span class="n">elementSize</span><span class="p">);</span><span class="w">              </span><span class="c1">// size</span><span class="w">
</span></span></span></code></pre></div><p>This copies from object <code>element</code>, starting at offset <code>firstFieldOffset</code>, into the raw memory address determined by <code>offset(index)</code>.</p>
<p>The <a href="https://bramp.github.io/unsafe/net/bramp/unsafe/UnsafeArrayList.html#get-int-">get</a> method is a little more problematic, as the List interface expects get to return an instance of the object. Since we aren’t actually storing references to the objects (but copies of their fields), we need to construct an instance and populate it. This is quite costly, and defeats the point of this UnsafeArrayList. Instead an additional <a href="https://bramp.github.io/unsafe/net/bramp/unsafe/UnsafeArrayList.html#get-T-int-">get</a> method is provided, that allows an object to be passed in, which will have its fields replaced.</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="line"><span class="cl"><span class="w">    </span><span class="kd">public</span><span class="w"> </span><span class="n">T</span><span class="w"> </span><span class="nf">get</span><span class="p">(</span><span class="n">T</span><span class="w"> </span><span class="n">dest</span><span class="p">,</span><span class="w"> </span><span class="kt">int</span><span class="w"> </span><span class="n">index</span><span class="p">)</span><span class="w"> </span><span class="p">{</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">        </span><span class="n">unsafe</span><span class="p">.</span><span class="na">copyMemory</span><span class="p">(</span><span class="kc">null</span><span class="p">,</span><span class="w"> </span><span class="n">offset</span><span class="p">(</span><span class="n">index</span><span class="p">),</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">                          </span><span class="n">dest</span><span class="p">,</span><span class="w"> </span><span class="n">firstFieldOffset</span><span class="p">,</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">                          </span><span class="n">elementSize</span><span class="p">);</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">        </span><span class="k">return</span><span class="w"> </span><span class="n">dest</span><span class="p">;</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">    </span><span class="p">}</span><span class="w">
</span></span></span></code></pre></div><p>For completeness a standard <code>get(int index)</code> method is provided, which creates a new instance of the object (using unsafe.allocateInstance() instead of <code>new Type</code>).</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="line"><span class="cl"><span class="w">    </span><span class="kd">public</span><span class="w"> </span><span class="n">T</span><span class="w"> </span><span class="nf">get</span><span class="p">(</span><span class="kt">int</span><span class="w"> </span><span class="n">index</span><span class="p">)</span><span class="w"> </span><span class="p">{</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">        </span><span class="k">return</span><span class="w"> </span><span class="n">get</span><span class="p">((</span><span class="n">T</span><span class="p">)</span><span class="w"> </span><span class="n">unsafe</span><span class="p">.</span><span class="na">allocateInstance</span><span class="p">(</span><span class="n">type</span><span class="p">),</span><span class="w"> </span><span class="n">index</span><span class="p">);</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">    </span><span class="p">}</span><span class="w">
</span></span></span></code></pre></div><p>You can inspect the rest of the <a href="https://github.com/bramp/unsafe/blob/master/unsafe-collection/src/main/java/net/bramp/unsafe/UnsafeArrayList.java">code via GitHub</a>, but these are the main parts.</p>
<p>In conclusion, this approach has some pros and cons, but was mostly created for fun.</p>
<ul>
<li>
<p>Pros</p>
</li>
<li>
<p>List&lt;&gt; interfaces that stores objects in contiguous memory</p>
</li>
<li>
<p>Better cache locality and CPU performance</p>
</li>
<li>
<p>Minimal memory overhead</p>
</li>
<li>
<p>Cons</p>
</li>
<li>
<p>Uses sun.misc.Unsafe</p>
</li>
<li>
<p>Additional CPU cycles needed to copies objects in and out of array</p>
</li>
<li>
<p>Copies the class out of the garbage collector’s view, thus if a stored object contains the only references to other objects, the garbage collector will not know it is still used.</p>
</li>
</ul>
<p>In the <a href="https://blog.bramp.net/post/2015/08/27/unsafe-part-3-benchmarking-a-java-unsafearraylist/">next article</a>, we&rsquo;ll benchmark this UnsafeArrayList, and investigate the performance impact of the cache locality, and other overheads.</p>
</description>
    </item>
    
    <item>
      <title>Unsafe Part 1: sun.misc.Unsafe Helper Classes</title>
      <link>https://blog.bramp.net/post/2015/08/24/unsafe-part-1-sun.misc.unsafe-helper-classes/</link>
      <pubDate>Mon, 24 Aug 2015 20:13:58 -0700</pubDate>
      
      <guid>https://blog.bramp.net/post/2015/08/24/unsafe-part-1-sun.misc.unsafe-helper-classes/</guid>
      <description><p>I recently came across the <a href="http://www.docjar.com/docs/api/sun/misc/Unsafe.html">sun.misc.Unsafe class</a>, a poorly documented, internal API that gives your java program direct access to the JVM’s memory. Of course accessing the JVM’s memory can be considered unsafe, but allows for some exciting opportunities.</p>
<p>You can use Unsafe to inspect and manipulate the layout of your objects in RAM, allocate memory off the heap, do interesting things with threads, or even <a href="http://mishadoff.com/blog/java-magic-part-4-sun-dot-misc-dot-unsafe/">hack in multiple inheritance</a>. Multiple people have <a href="https://dzone.com/articles/understanding-sunmiscunsafe">written about Unsafe</a> before, and there are some really <a href="http://mydailyjava.blogspot.com/2013/12/sunmiscunsafe.html">good articles</a>, so we won’t cover it here.</p>
<p>Using unsafe is not too difficult, but I found the need for a few helper methods, thus I created a collection of classes wrapping the Unsafe code, starting with <a href="https://bramp.github.io/unsafe/index.html?net/bramp/unsafe/UnsafeHelper.html">UnsafeHelper</a>. The main methods of interest are <a href="https://bramp.github.io/unsafe/net/bramp/unsafe/UnsafeHelper.html#getUnsafe--">getUnsafe()</a>, <a href="https://bramp.github.io/unsafe/net/bramp/unsafe/UnsafeHelper.html#sizeOf-java.lang.Object-">sizeOf()</a>, <a href="https://bramp.github.io/unsafe/net/bramp/unsafe/UnsafeHelper.html#firstFieldOffset-java.lang.Class-">firstFieldOffset()</a>, <a href="https://bramp.github.io/unsafe/net/bramp/unsafe/UnsafeHelper.html#toByteArray-java.lang.Object-">toByteArray()</a> and <a href="https://bramp.github.io/unsafe/net/bramp/unsafe/UnsafeHelper.html#hexDump-java.io.PrintStream-java.lang.Object-">hexDump()</a>. The <a href="https://bramp.github.io/unsafe/">javadoc</a> is the best place to look for documentation, however I’ll quickly explain their use.</p>
<p>To get an sun.misc.Unsafe instance, you have to extract it from a private static field within sun.misc.Unsafe class. For ease, the <a href="https://bramp.github.io/unsafe/net/bramp/unsafe/UnsafeHelper.html#getUnsafe--">UnsafeHelper.getUnsafe()</a> method does that.</p>
<p>When accessing an object, you typically need to know the size of the object (in bytes), and be able to find the offset to individual fields. If you <a href="http://www.codeinstructions.com/2008/12/java-objects-memory-structure.html">understand the memory layout</a> the JVM uses, you’ll know there is a header in front of the Object’s fields. Typically it looks like this, but varies based on CPU architecture, platform, etc:</p>
<table class="table table-bordered" style="margin-bottom: 0px">
  <tr>
    <th class="text-center">0</th>
    <th class="text-center">1</th>
    <th class="text-center">2</th>
    <th class="text-center">3</th>
    <th class="text-center">4</th>
    <th class="text-center">5</th>
    <th class="text-center">6</th>
    <th class="text-center">7</th>
    <th class="text-center">8</th>
    <th class="text-center">9</th>
    <th class="text-center">10</th>
    <th class="text-center">11</th>
    <th class="text-center">12</th>
    <th class="text-center">13</th>
    <th class="text-center">14</th>
    <th class="text-center">15</th>
  </tr>
  <tr>
    <td class="text-center" colspan="8">mark word(8)</td>
    <td class="text-center" colspan="4">klass pointer(4)</td>
    <td class="text-center" colspan="4">padding</td>
  </tr>
</table>
<div class="text-right">More information [here][6] and [here][7].</div>
<p>To hide some of the details, <a href="https://bramp.github.io/unsafe/net/bramp/unsafe/UnsafeHelper.html#headerSize-java.lang.Object-">headerSize()</a> returns the size of the header, and <a href="https://bramp.github.io/unsafe/net/bramp/unsafe/UnsafeHelper.html#sizeOf-java.lang.Object-">sizeOf()</a> return the total size an object including the header in bytes. <a href="https://bramp.github.io/unsafe/net/bramp/unsafe/UnsafeHelper.html#firstFieldOffset-java.lang.Class-">firstFieldOffset()</a> is then useful as it provides the the offset to the first field. Note that <a href="https://bramp.github.io/unsafe/net/bramp/unsafe/UnsafeHelper.html#headerSize-java.lang.Object-">headerSize()</a> and <a href="https://bramp.github.io/unsafe/net/bramp/unsafe/UnsafeHelper.html#firstFieldOffset-java.lang.Class-">firstFieldOffset()</a> do not always return identical results, as padding (not part of the header) may be used to correctly align the first field.</p>
<p>Next <a href="https://bramp.github.io/unsafe/net/bramp/unsafe/UnsafeHelper.html#toByteArray-java.lang.Object-">toByteArray()</a> will take an object, and copy it (and its header) into a byte array. Useful for easily inspecting, and serialising the object. Finally, <a href="https://bramp.github.io/unsafe/net/bramp/unsafe/UnsafeHelper.html#hexDump-java.io.PrintStream-java.lang.Object-">hexDump()</a> uses the <a href="https://bramp.github.io/unsafe/net/bramp/unsafe/UnsafeHelper.html#toByteArray-java.lang.Object-">toByteArray()</a> to grab an object, and print out a hex representation of the memory, for example:</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="line"><span class="cl"><span class="cm">/**
</span></span></span><span class="line"><span class="cl"><span class="cm"> * hexDump(new Class4()) prints:
</span></span></span><span class="line"><span class="cl"><span class="cm"> * 0x00000000: 01 00 00 00 00 00 00 00  8A BF 62 DF 67 45 23 01
</span></span></span><span class="line"><span class="cl"><span class="cm"> */</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="kd">static</span><span class="w"> </span><span class="kd">class</span> <span class="nc">Class4</span><span class="w"> </span><span class="p">{</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">    </span><span class="kt">int</span><span class="w"> </span><span class="n">i</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="n">0x01234567</span><span class="p">;</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="p">}</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="cm">/**
</span></span></span><span class="line"><span class="cl"><span class="cm"> * Longs are always 8 byte aligned, so 4 bytes of padding
</span></span></span><span class="line"><span class="cl"><span class="cm"> * hexDump(new Class8()) prints:
</span></span></span><span class="line"><span class="cl"><span class="cm"> * 0x00000000: 01 00 00 00 00 00 00 00  9B 81 61 DF 00 00 00 00
</span></span></span><span class="line"><span class="cl"><span class="cm"> * 0x00000010: EF CD AB 89 67 45 23 01
</span></span></span><span class="line"><span class="cl"><span class="cm"> */</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="kd">static</span><span class="w"> </span><span class="kd">class</span> <span class="nc">Class8</span><span class="w"> </span><span class="p">{</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">    </span><span class="kt">long</span><span class="w"> </span><span class="n">l</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="n">0x0123456789ABCDEFL</span><span class="p">;</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="p">}</span><span class="w">
</span></span></span></code></pre></div><p>In the first example, Class4, a simple class with a single int field, takes up 16 bytes of memory, with the first 8 used by the JVM, the 2nd 4 bytes being a class pointer (basically how the object knows what kind of class it is), and the last four actually being the value of the field. The second example shows a similar header, but with bytes 12-16 being used as padding, so that the long field value is 8 byte aligned.</p>
<p>These helper methods are available in <a href="https://github.com/bramp/unsafe">new project on Github</a>, and downloadable via Maven. Just <a href="https://oss.sonatype.org/service/local/repositories/releases/content/net/bramp/unsafe/unsafe-helper/1.0/unsafe-helper-1.0.jar">download the jar file</a>, or include a maven dependency, and <code>import net.bramp.unsafe.UnsafeHelper</code>.</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-xml" data-lang="xml"><span class="line"><span class="cl"><span class="nt">&lt;dependency&gt;</span>
</span></span><span class="line"><span class="cl">    <span class="nt">&lt;groupId&gt;</span>net.bramp.unsafe<span class="nt">&lt;/groupId&gt;</span>
</span></span><span class="line"><span class="cl">    <span class="nt">&lt;artifactId&gt;</span>unsafe-helper<span class="nt">&lt;/artifactId&gt;</span>
</span></span><span class="line"><span class="cl">    <span class="nt">&lt;version&gt;</span>1.0<span class="nt">&lt;/version&gt;</span>
</span></span><span class="line"><span class="cl"><span class="nt">&lt;/dependency&gt;</span>
</span></span></code></pre></div><p><a href="https://blog.bramp.net/post/2015/08/26/unsafe-part-2-using-sun.misc.unsafe-to-create-a-contiguous-array-of-objects/">Next article</a>, we&rsquo;ll make use of this new UnsafeHelper to build a special List which copies objects, instead of storing references.</p>
</description>
    </item>
    
    <item>
      <title>Decompile and Recompile Android APK</title>
      <link>https://blog.bramp.net/post/2015/08/01/decompile-and-recompile-android-apk/</link>
      <pubDate>Sat, 01 Aug 2015 12:24:59 -0700</pubDate>
      
      <guid>https://blog.bramp.net/post/2015/08/01/decompile-and-recompile-android-apk/</guid>
      <description><p>I had the need to take an existing <a href="https://en.wikipedia.org/wiki/Android_application_package">Android APK</a>, tweak it, and rebuild. This is not too difficult, but I did have to download the tools from a few different sites, and find a full list of instructions. Thus to make this easier, here is a quick recap of what&rsquo;s needed.</p>
<p>Download the following:</p>
<ul>
<li><a href="http://ibotpeaches.github.io/Apktool/">apktool</a> - tool for reverse engineering Android apk files. In this case can extract and rebuild.</li>
<li><a href="https://docs.oracle.com/javase/8/docs/technotes/tools/unix/keytool.html">keytool</a> - Java tool for creating keys/certs. Comes with the JDK.</li>
<li><a href="https://docs.oracle.com/javase/8/docs/technotes/tools/unix/jarsigner.html">jarsigner</a> Java tool for signing JAR/APK files. Comes with the JDK.</li>
<li><a href="https://developer.android.com/tools/help/zipalign.html">zipalign</a> - archive alignment tool, that comes with the Android SDK.</li>
</ul>
<p>Some extras:</p>
<ul>
<li><a href="http://jd.benow.ca/">JD-GUI</a> - Java Decompiler</li>
<li><a href="https://github.com/pxb1988/dex2jar">dex2jar</a> - Converts Android dex files to class/jar files.</li>
</ul>
<h2 id="instructions">Instructions:</h2>
<p>We assume you are on a Linux or Mac, but this will work (with some tweaking) on Windows. Install a recent Java JDK, then the <a href="https://developer.android.com/sdk/installing/index.html?pkg=tools">Stand-alone Android SDK</a>, and finally <a href="http://ibotpeaches.github.io/Apktool/">apktool</a>.</p>
<p>Optionally setup some alias:</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-bash" data-lang="bash"><span class="line"><span class="cl"><span class="nb">alias</span> <span class="nv">apktool</span><span class="o">=</span><span class="s1">&#39;java -jar ~/bin/apktool_2.0.1.jar&#39;</span>
</span></span><span class="line"><span class="cl"><span class="nb">alias</span> <span class="nv">dex2jar</span><span class="o">=</span><span class="s1">&#39;~/bin/dex2jar-2.0/d2j-dex2jar.sh&#39;</span>
</span></span><span class="line"><span class="cl"><span class="nb">alias</span> jd-gui<span class="o">=</span><span class="s1">&#39;java -jar ~/bin/jd-gui-1.3.0.jar&#39;</span>
</span></span></code></pre></div><p>First, unpack the application.apk file. This will create a &ldquo;application&rdquo; directory with assets, resources, compiled code, etc.</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-bash" data-lang="bash"><span class="line"><span class="cl">apktool d -r -s application.apk
</span></span></code></pre></div><p>Now poke around, and edit any of the files in the application directory. If you wish to decompile any java you can do the following:</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-bash" data-lang="bash"><span class="line"><span class="cl"><span class="c1"># Convert the Dex files into standard class files</span>
</span></span><span class="line"><span class="cl">dex2jar application/classes.dex
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl"><span class="c1"># Now use the JD (Java Decompiler) to inspect the source</span>
</span></span><span class="line"><span class="cl">jd-gui classes-dex2jar.jar
</span></span></code></pre></div><p>Once you have made your changes, you need to repack the APK. This will create a <code>my_application.apk</code> file:</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-bash" data-lang="bash"><span class="line"><span class="cl">apktool b -f -d application
</span></span><span class="line"><span class="cl">mv application/dist/application.apk my_application.apk
</span></span></code></pre></div><p>The APK must be signed before it will run on a device. Create a key if you don&rsquo;t have an existing one. If prompted for a password, enter anything (but remember it).</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-bash" data-lang="bash"><span class="line"><span class="cl">keytool -genkey -v -keystore my-release-key.keystore -alias alias_name <span class="se">\
</span></span></span><span class="line"><span class="cl">                   -keyalg RSA -keysize <span class="m">2048</span> -validity <span class="m">10000</span>
</span></span></code></pre></div><p>Now sign the APK with the key:</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-bash" data-lang="bash"><span class="line"><span class="cl"><span class="c1"># Sign the apk</span>
</span></span><span class="line"><span class="cl">jarsigner -verbose -sigalg SHA1withRSA -digestalg SHA1 -keystore my-release-key.keystore my_application.apk alias_name
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl"><span class="c1"># Verify apk</span>
</span></span><span class="line"><span class="cl">jarsigner -verify -verbose -certs my_application.apk
</span></span></code></pre></div><p>Finally, the apk must be aligned for optimal loading:</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-bash" data-lang="bash"><span class="line"><span class="cl">zipalign -v <span class="m">4</span> my_application.apk my_application-aligned.apk
</span></span></code></pre></div><p>Voila, now you have a <code>my_application-aligned.apk</code> file, which you can side load onto your device.</p>
</description>
    </item>
    
    <item>
      <title>Grabbing a Certificate with OpenSSL and importing it into Java</title>
      <link>https://blog.bramp.net/post/2014/08/16/grabbing-a-certificate-with-openssl-and-importing-it-into-java/</link>
      <pubDate>Sat, 16 Aug 2014 00:00:00 +0000</pubDate>
      
      <guid>https://blog.bramp.net/post/2014/08/16/grabbing-a-certificate-with-openssl-and-importing-it-into-java/</guid>
      <description><p>Occasionally I have to grab a SSL cert from a server, and turn it into something that Java can use. Here are the quick instructions</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-bash" data-lang="bash"><span class="line"><span class="cl"><span class="c1"># Store the cert issued by a web server</span>
</span></span><span class="line"><span class="cl">openssl s_client -showcerts -connect www.google.com:443 <span class="p">&amp;</span>gt<span class="p">;</span> www.google.com.pem
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl"><span class="c1"># Convert it from PEM format to DER format</span>
</span></span><span class="line"><span class="cl">openssl x509 -in www.google.com.pem -inform PEM -out www.google.com.der -outform DER
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl"><span class="c1"># Import it into your keystore</span>
</span></span><span class="line"><span class="cl">sudo /usr/java6/bin/keytool -import -alias www.google.com -file www.google.com.der -keystore /usr/java6/jre/lib/security/cacerts
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl"><span class="c1"># The keystore password is by default &#34;changeit&#34;</span>
</span></span></code></pre></div></description>
    </item>
    
    <item>
      <title>Groovy / Grails</title>
      <link>https://blog.bramp.net/post/2012/07/04/groovy-grails/</link>
      <pubDate>Wed, 04 Jul 2012 00:00:00 +0000</pubDate>
      
      <guid>https://blog.bramp.net/post/2012/07/04/groovy-grails/</guid>
      <description><p>Over the past couple of weeks I’ve been playing with Groovy and Grails, and after a somewhat frustrainting week I thought I’d share my thoughts. <a href="http://groovy.codehaus.org/" title="Groovy">Groovy</a> is a dynamic language that runs in a standard JVM, and effectively extends the Java langugage. This makes it easy for existing Java programmer to pick it up and ease into it. <a href="http://grails.org/">Grails</a> is the Groovy equilivant of <a href="http://rubyonrails.org/">Ruby on Rails</a>, a rapid web development framework. I had high hopes for both as Groovy adds lots of interesting features to Java, such as <a href="http://en.wikipedia.org/wiki/Closure_(computer_science)">Closures</a>, <a href="http://en.wikipedia.org/wiki/Type_system">Dynamic typing</a>, <a href="http://en.wikipedia.org/wiki/Mixin">Mixins</a>, and lots of clever syntax to reduce code and to speed up the average developer. On top of this Grails can quickly scaffold a <a href="http://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93controller">MVC</a> framework, allowing you to literally build a <a href="http://en.wikipedia.org/wiki/Create,_read,_update_and_delete">CRUD</a> based application in minutes.</p>
<p>This all sounds great but I think both of these technologies are still young and there are a lot of things to work out. I was consistently hitting bugs in Grails, and I found the support for Groovy to be lacking in my IDE of choice Ecplise, forcing me to move to IntelliJ which did a lot better job.</p>
<h1 id="groovy">Groovy</h1>
<h2 id="dynamic-typing">Dynamic typing</h2>
<p>The dynamic variable typing allows you to create a variable and not declare what type it is. Then as you use the variable you can very easily convert it between types. To be honest, and maybe I miss the point, but I’ve never been fond of dynamic typing in other languages. I tend to create a variable and ensure I keep it a particular type. I do this because dynamic typing can introduce all sorts of errors, and you have to truely understand the rules. For example, if I try and convert a String to a boolean (as I might do in a condition), what type of Strings evaluate to true and false? In Groovy a empty string is false, but a string with a single whitespace char would be true.</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-groovy" data-lang="groovy"><span class="line"><span class="cl"><span class="kt">def</span> <span class="n">someString</span> <span class="o">=</span> <span class="s2">&#34;&#34;</span>
</span></span><span class="line"><span class="cl"><span class="k">if</span> <span class="o">(</span><span class="n">someString</span><span class="o">)</span> <span class="o">{</span>
</span></span><span class="line"><span class="cl"><span class="o">...</span>
</span></span><span class="line"><span class="cl"><span class="o">}</span>
</span></span><span class="line"><span class="cl"><span class="c1">// a useful example of String-&amp;gt;boolean conversion
</span></span></span></code></pre></div><p>Groovy also adds <a href="http://en.wikipedia.org/wiki/Duck_typing">duck typing</a>. If a variable walks like a duck, quacks like a duck then it must be a duck. This is effectively a way to avoid having to implement a interface by checking at runtime if the class has a particular method. This is only useful because at runtime Groovy allows methods to be add (and removed) from classes. This thus allow from some interesting programming, however I find it very error prone. As a method could be added to a class at runtime there is no compile-time checking.</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-groovy" data-lang="groovy"><span class="line"><span class="cl"><span class="kd">class</span> <span class="nc">SomeObject</span> <span class="o">{</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl"><span class="o">}</span>
</span></span><span class="line"><span class="cl"><span class="n">SomeObject</span> <span class="n">o</span> <span class="o">=</span> <span class="k">new</span> <span class="n">SomeObject</span><span class="o">();</span>
</span></span><span class="line"><span class="cl"><span class="n">o</span><span class="o">.</span><span class="na">someMethod</span><span class="o">();</span>
</span></span><span class="line"><span class="cl"><span class="c1">// This code is valid at compile time, but only at runtime with an MissingMethod exception be thrown.
</span></span></span></code></pre></div><p>Because of the dynamic nature a lot of the silly typo errors that should be caught at compile time, will only now be found at run time. Mistyping a method name wasn’t caught until that line of code was reached. Also, due to dynamic typing, errors such as calling a method with the wrong argument types were not caught. I found this very frustrating as it slowed down my development.  This also makes me dread what will happen if this code is pushed into production without a very rigorous 100% line test coverage.</p>
<p>It looks like Groovy 2.0 is trying to resolve this concern with <a href="http://docs.codehaus.org/display/GroovyJSR/GEP+8+-+Static+type+checking">GEP 8</a>, a new type of annotation that will force Groovy to statically check your class/method at compile time.</p>
<h1 id="grails">Grails</h1>
<h2 id="gorm">GORM</h2>
<p>The GORM is Grails’s <a href="http://en.wikipedia.org/wiki/Object-relational_mapping">ORM</a>, which sits on top of <a href="http://www.hibernate.org/">Hibernate</a>. It takes advantage of Groovy’s <a href="http://groovy.codehaus.org/Collections">collection syntax</a> to make configuring a model easy. However, I think due to the young nature of Grails I found multiple problems with GORM. I started by using the super convenient <a href="http://www.h2database.com/">H2</a> data source for testing. Then as I progressed I moved to MySQL. However, the code that worked perfectly with with H2 stopped working in MySQL. There were little things, like reserved keywords being different, which tripped up MySQL. Looking at the generated SQL the MySQL queries weren’t being escaped, which would have solved this issue. Secondly, and a bigger issue, but I was using hierarchical data models. That is, I had a generic abstract Base model, and multiple specific models that extended from the base. This worked well in H2 and avoided a lot of duplication of code, but with the MySQL data source it was handled incorrectly, causing me to spend hours investigating and modifying the code.</p>
<p>I also tried the <a href="http://grails.org/plugin/mongodb">MongoDB plugin</a>, as the document store concept works great for my heirachy concept. However it wasn’t a direct drop in replacement for H2/MySQL, and I even found some bugs, which I <a href="http://jira.grails.org/browse/GPMONGODB-210">reported</a>.</p>
<h2 id="scaffolding">Scaffolding</h2>
<p>This was one of the coolest features, but also one of the biggest let downs. Scaffolding generates all the code you quickly need for a simple CRUD application. There are two modes, dynamic and static. A dynaimic one literally allows you to create a controller in just a few lines, with all the code for create/read/update/delete hidden behind the scenes. Static scaffolding is very similar in features, but placed all the code in the groovy file ready for you to edit.</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-groovy" data-lang="groovy"><span class="line"><span class="cl"><span class="kd">class</span> <span class="nc">SomeController</span> <span class="o">{</span>
</span></span><span class="line"><span class="cl">    <span class="kd">static</span> <span class="n">scaffold</span> <span class="o">=</span> <span class="n">Author</span>
</span></span><span class="line"><span class="cl"><span class="o">}</span>
</span></span><span class="line"><span class="cl"><span class="c1">// This is all you need for a CRUD controller that maps to the Author model
</span></span></span></code></pre></div><p>The problem I found here is that it dynamic scaffolding served little purpose than showing off how little you could write. To actually customise it you would have to use static scaffolding. Even then, the static scaffolding didn’t seem particular neat and simple (as compared to other rapid dev frameworks I’ve used), and you eventually had to throw 90% of that generated code away and write it all yourself.</p>
<h2 id="closures">Closures</h2>
<p>The concept of closures and anonymous functions is a very cool one, which in fact I have quite liked using in Python and JavaScript. The implementation here also seemed quite good, except for some minor pet pevs I had. The real issue I had with closures is how it polluted the call stack. Some of my call stacks were now chains of methods like:</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-text" data-lang="text"><span class="line"><span class="cl">at _GrailsCompile_groovy$_run_closure2.doCall(_GrailsCompile_groovy:46)
</span></span><span class="line"><span class="cl">at com.springsource.loaded.ri.ReflectiveInterceptor.jlrMethodInvoke(ReflectiveInterceptor.java:1231)
</span></span><span class="line"><span class="cl">at org.codehaus.gant.GantMetaClass.invokeMethod(GantMetaClass.java:133)
</span></span><span class="line"><span class="cl">at com.springsource.loaded.ri.ReflectiveInterceptor.jlrMethodInvoke(ReflectiveInterceptor.java:1231)
</span></span><span class="line"><span class="cl">at org.codehaus.gant.GantMetaClass.invokeMethod(GantMetaClass.java:133)
</span></span></code></pre></div><p>This is no doubt a limitation of being built onto of the JVM that couldn’t provide more helpful output.</p>
<h2 id="run-app">Run-app</h2>
<p>Grails comes with a CLI tool that does a lot of the code generation for you. One of the useful commands is <code>grails run-app</code>, this will start up an embedded webserver which runs your application, and better yet, allows you to make code changes without recompiling/redeploying. This truly makes it quicker to develop and test your Java/Groovy, and allows those minor tweaks to your Controllers, etc without a wait. However, yet again I was let down by this feature. Lots of simple changes would cause the run-app to stop serving my pages with odd exception. The solution was to stop the webserver and start it again, which defeats the purpose. Even worse, I sometimes had to <code>grails clean</code> as it did not always pick up my code changes.</p>
<h1 id="conclusion">Conclusion</h1>
<p>I liked everything that Groovy and Grails was trying to do, but I think their implementation isn’t good enough yet, and there are too many gotchas for me to considering using this in a production environment. I no doubt will follow it’s progress and play with it every so often.</p></description>
    </item>
    
  </channel>
</rss>
