<?xml version="1.0" encoding="UTF-8" ?>

<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom">
<channel>
   
   	<title>RealJenius.com - Tag: java</title>
   
   <link>http://realjenius.com</link>
   <description>I'm a software developer in the game industry, and have been (for better or worse) coding on the Java platform for the last decade. I also do all my own stunts.</description>
   <language>en-us</language>
   <managingEditor>R.J. Lorimer</managingEditor>
   <atom:link href="rss" rel="self" type="application/rss+xml" />
   
	<item>
  <title>JEP-171: Fence Intrisics Keep Memory In Line</title>
  <link>http://realjenius.com/2012/12/03/jep171-fences/</link>
  <author>R.J. Lorimer</author>
  <pubDate>2012-12-03T00:00:00-08:00</pubDate>
  <guid>http://realjenius.com/2012/12/03/jep171-fences/</guid>
  <description><![CDATA[
     <p>Doug Lea just posted a new Java enhancement proposal with <a href='http://openjdk.java.net/jeps/171'>JEP-171 - Fence Intrinsics</a>. This enhancement is all about exposing memory fence controls into Java code so that the <code>java.util.concurrent</code> APIs can more accurately and efficiently control memory ordering and bounding.</p>

<p>This is an interesting JEP as it proposes no Java consumer-oriented APIs; the only changes would be on the <code>sun.misc.Unsafe</code> class - which is already a fascinating pivot point for many of the advanced concurrency features of Java. Here is a Stack Overflow article that recaps many of them better than I could: <a href='http://stackoverflow.com/questions/5574241/interesting-uses-of-sun-misc-unsafe'>StackOverflow.com: &#8220;Interesting Uses of sun.misc.Unsafe&#8221;</a>. This class (as you can guess from the package) is <em>not</em> intended for regular Java devs to access; it&#8217;s an implementation-specific class, and is really only meant for internal use by class library devs on the JDK. <em>(That said, many folks have taken this class by the horns to wrangle the most out of the JVM anyway.)</em></p>

<p>What is proposed instead is to make ordering fences with memory a first-class citizen in the implementation layer of the JDK so that the various core APIs for concurrency can leverage fencing without having to resort on side-effects of other lower-level intrinsics (something that is done regularly today).</p>

<p>You may be asking why memory fencing is important. Modern CPUs can easily re-order memory accessing and storing when it can see via the upcoming instruction set that re-ordering will not impact the overall outcome of the program as considered by a single thread in the CPU. When you start throwing multiple threads or CPUs at a problem, out-of-order operations on memory that would otherwise go un-noticed could instead cause all kinds of data corruption and confusion. That&#8217;s why effectively all of the core synchronization and atomic operations in Java today implicitly carry a memory fence along with them; it&#8217;s part of the larger equation of protecting memory access.</p>

<p>This JEP includes three operations in the proposal:</p>

<ul>
<li><code>Unsafe.loadFence()</code> - Prevent reordering of load operations before this call with loads and stores after this call.</li>

<li><code>Unsafe.storeFence()</code> - Prevent reordering of store operations before this call with loads and stores after this call.</li>

<li><code>Unsafe.fullFence()</code> - Prevent reordering of <strong>all</strong> memory operations before this call with loads and stores after this call.</li>
</ul>

<p>You can read more about memory fences in the Wikipedia <a href='http://en.wikipedia.org/wiki/Memory_barrier'>Memory Barrier</a> article.</p>

<p>It&#8217;s worth noting that the JEP does consider potentially surfacing memory fence operations to full devs at some point in the future given that <code>sun.misc.Unsafe</code> is already platform specific (making it risky for external libs to access), and may become <em>impossible</em> to access given the efforts of Jigsaw:</p>

<blockquote>
<p>Adding these methods at the VM level permits use by JDK libraries in support of JDK 8 features, while also opening up the possibility of later exporting the base functionality via new java.util.concurrent APIs. This may become essential to allow people developing non-JDK low-level libraries if upcoming modularity support makes these methods impossible for others to access.</p>
</blockquote>
  ]]></description>
</item>

	<item>
  <title>The Madness of Tunneling JMX is Over!</title>
  <link>http://realjenius.com/2012/11/21/java7-jmx-tunneling-freedom/</link>
  <author>R.J. Lorimer</author>
  <pubDate>2012-11-21T00:00:00-08:00</pubDate>
  <guid>http://realjenius.com/2012/11/21/java7-jmx-tunneling-freedom/</guid>
  <description><![CDATA[
     <p>I work with an immense number of clients running our software, and in turn, an immense number of servers in the wild. Generally speaking, I am playing a role of support and debugging, and one of the facilities we leverage to the hilt in our platform to help us here is JMX.</p>

<p>MBeans give us a tremendous amount of access into the running system, and are a good standardized way to publish the management tools. Unfortunately, they are a tremendous pain in the ass to get access to in a secure system.</p>

<p>Generally what I am given for any system we connect to is my own SSH key or SSH credentials, and possibly one or two ports popped open with pinholes for my IP address. The latter I can provide for myself with SSH tunnelling if I need to. Unfortunately, this isn&#8217;t enough for JMX.</p>

<p>JMX runs on top of RMI, and as such, there are two ports that JMX utilizes:</p>

<ul>
<li>The JMX connect port.</li>

<li>The (infamously) roaming RMI data port.</li>
</ul>

<p>In all recent builds of Oracle Java, you can affix the first port via this system property when starting the Java program:</p>
<div class='highlight'><pre><code class='bash'>-Dcom.sun.management.jmxremote.port<span class='o'>=</span>1099
</code></pre>
</div>
<p>Unfortunately, the second port has no mechanism for assignment. This means that you either need (a) the entire firewall cracked wide open for your IP address, or (b) you need to run a dynamic socks proxy and route your particular JMX tool through the proxy. The latter is generally the only real option. You then have the added complexity that the hostname you connect to needs to match the value of <code>java.rmi.server.hostname</code>, which in cloud solutions that do complex things with IP addresses (I&#8217;m looking at your EC2), only makes it even harder to get right.</p>

<p>Thankfully (and I do mean thankfully), not anymore for systems running Java 7u4 or higher. <a href='http://hirt.se/blog/'>Marcus Hirt</a> has blogged about <a href='http://hirt.se/blog/?p=289'>the new RMI binding property</a> that has come to Java since the merger with JRockit.</p>

<blockquote>
<p>Now, one handy but often overlooked feature that entered the 7u4 JDK as part of the JRockit convergence, was the ability to specify the port of the RMI server. By setting the port used by the RMI registry and the RMI server to the same port, tunneling will be much easier. Now, the name of the property for setting the port of the RMI Server was slightly changed from the JRockit implementation, and is now called com.sun.management.rmi.port, instead of com.sun.management.rmiserver.port. Here is an example of how to enable the external management agent with the same RMI registry and RMI server port on the command line, in JDK 7u4 and later:</p>

<p>java -Dcom.sun.management.jmxremote.port=7091 -Dcom.sun.management.jmxremote.rmi.port=7091 -Dcom.sun.management.jmxremote.authenticate=false -Dcom.sun.management.jmxremote.ssl=false</p>
</blockquote>

<p>I cannot stress enough how much this should help those of us dealing with firewalled systems and JMX. Kudos!</p>
  ]]></description>
</item>

	<item>
  <title>JEP-155: New Concurrency Utils Part 1 - Atomically Delicious</title>
  <link>http://realjenius.com/2012/11/18/jep155-numerics/</link>
  <author>R.J. Lorimer</author>
  <pubDate>2012-11-18T00:00:00-08:00</pubDate>
  <guid>http://realjenius.com/2012/11/18/jep155-numerics/</guid>
  <description><![CDATA[
     <p>Concurrency geeks rejoice! Doug Lea and the JSR166 exper group are a perpetual fountain of classes, constructs, and frameworks for multi-threading, and they are at it once again; working to funnel more amazing roflscale concurrency primitives and not-so-primitives into Java 8 - this time in the form of <a href='http://openjdk.java.net/jeps/155'>JEP 155: Concurrency Updates</a>.</p>

<p>There are a number of enhancements being proposed in this JEP, so I&#8217;ll probably tackle it in a few blog posts. For today, we&#8217;ll talk numbers!</p>

<h2 id='atomicish_numbers'>Atomic-ish Numbers</h2>

<p>It&#8217;s very very common to use atomic values in metrics gathering capacities in Java application. Applications everywhere (if they know what is good for them) are doing things like tracking total execution time, # of executions, and max execution time for as many data points as they can stomach.</p>

<p>Compared to the &#8220;olden days&#8221; of Java, atomics (particularly <code>java.util.concurrent.atomic.AtomicLong</code>) are a huge boon for this as they get rid of the overhead caused by contention when you&#8217;re dealing with synchronization. A particular code-flow will be much more concurrent when updating an atomic value than trying to fence through a synchronization boundary in heavy traffic.</p>

<p>However, all is not well in atomic land. While they are much better than everything that has come before them, they can still be quite disruptive. Updating an atomic value is, by definition, still fully shared between threads. While it&#8217;s a narrow operation, the guarantee is that after the operation is done, all CPU active on the system will see the same value in that memory location. To do this, the CPU core doing the work has to ensure that the value of that atomic is pushed back out to main memory; not just retained in the CPU cache. And in so doing, it has to keep trying to update the core memory until the incremental is what is expected (via a CAS - <a href='http://en.wikipedia.org/wiki/Compare-and-swap'>compare and swap</a> operation). This CAS and memory fence ensures that staleness does not happen due to the CPU keeping data in local cache only, and not dumping out to slow system memory constantly.</p>

<p>However, this inherently means that, for this value, we <em>are</em> writing out to slow system memory constantly. So it&#8217;s not free. Additionally, what often can happen is that the atomic changing invalidates a line of cache shared by multiple values. This is fairly common because the contiguous cache blocks the CPU is designed to invalidate are generally large enough to hold multiple numeric values. This means that the CPU is forced to (unintentionally) re-fence multiple atomics; often atomics that are allocated together for the same data structure.</p>

<p>This lack of cache coherence and affinity can be a very real, and very hidden cost with all fence operations. Martin Thompson and Michael Barker (the wizards behind the much discussed <a href='http://martinfowler.com/articles/lmax.html'>LMAX Architecture</a> and the <a href='http://lmax-exchange.github.com/disruptor/'>disruptor stream processing framework</a>) have a talk that covers this problem (and many others) in detail titled <a href='http://www.infoq.com/presentations/Lock-free-Algorithms#HN2'>Lock-Free Algorithms</a>.</p>

<p>Thompson and Barker show exactly how much this cache issue can impact performance, and how with a little adjusting, the atomic classes can be designed with what they call &#8220;mechanical sympathy&#8221; in mind; in other words, built to avoid sharing cache regions with other atomic values. So instead of this:</p>
<div class='highlight'><pre><code class='text'>cache line 1 . . . . &lt;atomic int val A&gt; . . . . . &lt;atomic int val B&gt; . . .
cache line 2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
</code></pre>
</div>
<p>You ideally would get this:</p>
<div class='highlight'><pre><code class='text'>cache line 1 . . . . &lt;atomic int val A&gt; . . . . . . . . . . . . . . . . .
cache line 2 . . &lt;atomic int val B&gt; . . . . . . . . . . . . . . . . . . .
</code></pre>
</div>
<p>Now the two values are isolated from each other, reducing cache damaging significantly.</p>

<p>While I&#8217;m listing interesting related reads, another article just popped up in the past couple days that shows some very real metrics for the problems you can hit with Atomics in terms of program throughput. Marc Brooker <a href='http://brooker.co.za/blog/2012/11/13/increment.html'>just posted how atomics and volatiles in Java work on x86</a>, and it shows exactly what a lack of mechanical sympathy can mean to your cache hit performance. The <code>perf stat</code> output he shows with the significant increase of <code>LLC-load-misses</code> is exactly what this padded cache is meant to mitigate as much as possible - of course, it can only do so much; the entire idea of an atomic implies there is some shared memory involvement, which is simply going to be slower. The goal is to narrow that slowness to specific values, as much as possible.</p>

<p>So mechanical sympathy changes help, but only get you so far. The work in JEP-155 doesn&#8217;t stop by exploring this idea. There is another issue with atomics as it pertains to being used for metrics-like monitoring in large scale Java systems. Their atomic requirement may actually be too stringent. Often times when you&#8217;re looking at something like an &#8220;average&#8221; execution time or &#8220;max&#8221; execution time, it&#8217;s acceptable to say the value can be eventually consistent across multiple updates. If there is a little margin for error (like you might miss one recent update on a read), it&#8217;s not going to impact your analysis in any real way.</p>

<p>Knowing this, the JSR166 folks have taken one of the ideas that are common in highly concurrent programming, and applied them to these types: striping, or segmenting.</p>

<p>If you&#8217;ve ever looked into the internals of the <code>ConcurrentHashMap</code> class, you may be familiar with the constructs it uses to minimize contention and avoid locking. Internally, the CHM uses a series of segments which represent sub-sections of the map, and can be worked with independently. By using multiple segments, the data structure is able to immediately divide the potential contention, at the expense of a little more memory used.</p>

<p><em>(Incidentally, the fastest JDBC connection pool I&#8217;ve ever benchmarked at scale uses this same mechanic to avoid pool contention - see <a href='https://github.com/wwadge/bonecp'>BoneCP</a>.)</em></p>

<p>This same idea is in place for a number of new atomic classes. There is an abstract <code>Striped64</code> super-class that holds a collection of <code>Cell</code> objects, which are really just Atomics with special padding to help with mechanical sympathy. The cells are created lazily as CAS updates fail due to contention. What this means is that a single instance of this may have several internal atomics representing the value in the aggregate. Since this class doesn&#8217;t just sit on the CAS wall until it updates successfully, it doesn&#8217;t have the same repeated crawling down into shared memory from the CPU cache. Instead it will retry a set number of times, and if it can&#8217;t get the first cell to update, it creates another one. The next one is a fully separate atomic in memory, and is bound by its own memory fencing and contention.</p>

<p>What&#8217;s interesting about this is since the atomics are intentionally written to avoid cache collisions, each one can be independently represented on a CPU, and since the class will try to balance the cells to individual threads, it will avoid causing the painful contentious updates altogether, making the most valuable use of the atomics. Each thread can say &#8220;If I created a new cell because a previous cell was contentious, I&#8217;ll keep using that new cell&#8221; - this means that CAS collisions can theoretically be eliminated over time, with the expense of potentially creating a larger memory footprint for a single number.</p>

<p>Since the cells are all independently update-able and create-able, and based on multiple iterative passes, the process of calculating a value over them involves iterating each cell and getting a snapshot value from them independently. Because of that, it&#8217;s possible that during the iteration, some of the cells may be slightly out of date or non existent on my local thread.</p>

<p>Additionally, since this is all based on combining the values out of multiple cells together, it immediately implies that there are only certain accumulative operations where this segmentation can be used.</p>

<p>There are several new classes that extend <code>Striped64</code> to provide relaxed-consistency classes for cases where you want to accumulate values in this way:</p>

<ul>
<li><code>LongAdder</code>; <code>DoubleAdder</code> - Classes that allow threads to accumulate values into a long or double in a thread-safe, and extremely low-contention path. <strong>Example Usage:</strong> Accumulating total execution time for a particular call so you can calculate average execution time.</li>

<li><code>LongMaxUpdater</code>; <code>DoubleMaxUpdater</code> - Classes that allow threads to calculate the &#8220;max&#8221; value seen up to a point, again in a very low-contention implementation. <strong>Example Usage:</strong> Tracking the max execution time for a particular method call.</li>

<li><code>LongAdderTable</code> - A handy extrapolation of long adder into a hash table form. This is an optimized map of LongAdders (although it doesn&#8217;t implement the Map interface for a number of reasons) that is specifically designed to be as efficient as possible in the use of long adder values per key, and allows for decrementing, incrementing, and adding by key. It also will create the adders for you automatically simply as an operation of you incrementing. <strong>Example Usage:</strong> Tracking several call execution times for an application all in one data structure.</li>
</ul>

<p>Let&#8217;s look at how these classes work internally to bring home the idea of cells for contention management. If we look at the <code>LongAdder</code> class as an example - let&#8217;s say we have a simple counter value we&#8217;re tracking for some method call, and it looks like this at one point:</p>
<div class='highlight'><pre><code class='text'>LongAdder
|
*-- Cell[0] = 51352
</code></pre>
</div>
<p>Our thread comes in to increment the first cell and we keep getting a CAS collision. So, based on the collision heuristics, we decide to create a new cell and increment there:</p>
<div class='highlight'><pre><code class='text'>LongAdder
|
*-- Cell[0] = 51494
|
*-- Cell[1] = 1
</code></pre>
</div>
<p>Note that Cell[0] has incremented several times outside of our control (other threads), and we also created Cell[1] to hold our new value.</p>

<p>To calculate the sum total for this long adder, we simply sum all of the cells together, returning <code>51495</code>.</p>

<p><em>The internal documentation on the <a href='http://gee.cs.oswego.edu/cgi-bin/viewcvs.cgi/jsr166/src/jsr166e/Striped64.java?view=markup'>Striped64</a> draft class has phenomenal notes on the algorithm)</em>.</p>

<p>While discussing atomic numbers, it should also be noted that there are implementations of <code>AtomicDouble</code> and <code>AtomicDoubleArray</code> laid out in the extras package of this draft work as well. These would ideally bring true atomic floating point to Java for the first time, but as indicated on the draft group site, the extras folder is probably not going to make it into Java 8 directly. They do show how these can be implemented, however, which is a feat in and of itself.</p>

<h2 id='whats_next'>What&#8217;s Next?</h2>

<p>There&#8217;s a good bit more in the JEP-155 bundle, including stamped locks and some nifty fork join improvements. Those are for another time, however.</p>
  ]]></description>
</item>

	<item>
  <title>Value Objects Proposal in Java with JEP 169</title>
  <link>http://realjenius.com/2012/11/10/values-objects-in-java/</link>
  <author>R.J. Lorimer</author>
  <pubDate>2012-11-10T00:00:00-08:00</pubDate>
  <guid>http://realjenius.com/2012/11/10/values-objects-in-java/</guid>
  <description><![CDATA[
     <p>There have been a lot of <a href='http://openjdk.java.net/jeps/0'>interesting JEPs</a> proposed recently for Java. With the pending onslaught of <a href='http://openjdk.java.net/projects/lambda/'>Lambdas</a>, and with them, an entirely new programming model, there is a whole new set of enhancements and opportunities for both the language and the JVM to expand.</p>

<p>One of the recently announced JEPs is <a href='http://openjdk.java.net/jeps/169'>JEP 169 - Value Objects</a>. Value objects are a number of tools for expicitly declaring that a Java object represents a raw set of vectorize-able values, rather than a composite set of memory values linked via pointers, and dynamically allocated on the heap.</p>

<p>As Java programmers, most of us are comfortable with (even if not entirely happy with) the distinction between primitives and objects. It&#8217;s one of those ugly, very un-academic pragmatics that you deal with because of the benefits it brings. Unfortunately, as the aforementioned JEP mentions, it&#8217;s also an ugly dividing line. You find yourself choosing between very low-level and hard-to-manage data structures and value types, or choosing more manageable high-level types, sacrificing the performance gains you would see otherwise:</p>

<blockquote>
<p>In modern JVMs, object allocation is inexpensive, with a cost comparable to out-of-line procedure calling. But even this cost is often a painful overhead when compared to individual operations on primitive values. Thus, Java programmers face a binary choice between existing primitive types (which avoid allocation) and other types (which allow data abstraction and other benefits of classes). When they need to define small composite values such as complex numbers, pixels, or pairs of return values, neither approach serves. This dilemma often has no good solution, and the workarounds distort Java programs and APIs. Consider, for example, the lack of a good complex number type for those who program numeric algorithms in Java.</p>
</blockquote>

<p>The general idea is allow programmers to give the JVM more knowledge about objects that are already designed to be immutable and simply represent a value, so that it can be treated in a more efficient way; much like primitives.</p>

<p>The example that is used repeatedly in the JEP is a class that represents a Complex number; call it <code>java.lang.Complex</code>. As you may or may not know, Java today doesn&#8217;t have a complex number value type. There are a number of open-source and academic examples of creating one, with the commonality between them being that they are written as a Java object. Usually, they are represented as a couple <code>double</code> values internally, and they have a numbef of methods for doing things like adding, subtracting, dividing, calculating cosine, and so forth. <a href='http://commons.apache.org/math/userguide/complex.html'>Apache-Commons Math</a> has a perfect example.</p>

<p>However, if you think about it, there is really no reason this Complex value has a full heap allocated object. It&#8217;s really just a couple primitives that are bound together inextricably. But the only way to do this with pure primitives would be to juggle multiple primitive values manually, and that&#8217;s not exactly a pretty API: hard to explain to implementors, and very hard to add functionality around. Sadly, a lot of APIs that have to deal with quickly shuffling numeric values (such as rendering APIs) fall into the trap of having to deal with buckets o&#8217; numbers.</p>

<p>This JEP is an attempt at tackling this problem. Once an object has been declared a value object, it can now be scalarized by the VM into a compact binary representation that can be propagated on the stack, and can even be interned in memory. In other words, the VM can treat the Complex class exactly like two <code>double</code> values held in a single memory vector; but the developer code can still handle it like an object, with all of the encapsulation and behavioral binding that implies.</p>

<p>Because the value object is being treated like a primitive, it now has no surrogate identity (no pointer location), and as such, it can&#8217;t be used for operations like synchronization and reference equality checks.</p>

<h2 id='boxing_benefits'>Boxing Benefits</h2>

<p>One of the interesting notes about this proposal is the fact that it changes the cost and complexity of boxing and unboxing of values from primitive types and back. Consider this contrived example:</p>
<div class='highlight'><pre><code class='java'><span class='kd'>public</span> <span class='kt'>void</span> <span class='nf'>someMethod</span><span class='o'>()</span> <span class='o'>{</span>
	<span class='kt'>int</span> <span class='n'>val1</span> <span class='o'>=</span> <span class='mi'>5</span><span class='o'>;</span>
	<span class='kt'>int</span> <span class='n'>val2</span> <span class='o'>=</span> <span class='mi'>10</span><span class='o'>;</span>
	<span class='kt'>int</span> <span class='n'>result</span> <span class='o'>=</span> <span class='n'>sumofsquares</span><span class='o'>(</span><span class='n'>a</span><span class='o'>,</span> <span class='n'>b</span><span class='o'>));</span>
	<span class='c1'>// ...</span>
<span class='o'>}</span>

<span class='kd'>public</span> <span class='n'>Integer</span> <span class='nf'>sumofsquares</span><span class='o'>(</span><span class='n'>Integer</span> <span class='n'>a</span><span class='o'>,</span> <span class='n'>Integer</span> <span class='n'>b</span><span class='o'>)</span> <span class='o'>{</span>
	<span class='k'>return</span> <span class='nf'>square</span><span class='o'>(</span><span class='n'>a</span><span class='o'>)</span> <span class='o'>+</span> <span class='n'>square</span><span class='o'>(</span><span class='n'>b</span><span class='o'>);</span>
<span class='o'>}</span>

<span class='kd'>public</span> <span class='n'>Integer</span> <span class='nf'>square</span><span class='o'>(</span><span class='n'>Integer</span> <span class='n'>val</span><span class='o'>)</span> <span class='o'>{</span>
	<span class='kt'>int</span> <span class='n'>val</span> <span class='o'>=</span> <span class='n'>val</span><span class='o'>.</span><span class='na'>intValue</span><span class='o'>();</span>
	<span class='k'>return</span> <span class='n'>val</span> <span class='o'>*</span> <span class='n'>val</span><span class='o'>;</span>
<span class='o'>}</span>
</code></pre>
</div>
<p>In this case, we have two primitive values in <code>someMethod()</code>, but immediately pass them into a method that expects boxed types. As such, the compiler is going to secretly inject code like this: <code>sumofsquares(Integer.valueOf(val1), Integer.valueOf(val2))</code>.</p>

<p>What this new value objects support would allow the compiler and runtime to do is defer any of boxing all the way until some complex behavior is invoked on the type - in this case that would be the <code>intValue()</code> invocation within the <code>square</code> method. However, since the compiler can determine it&#8217;s simply calling a method that returns the value component contained there-in, it can actually completely eliminate the boxing altogether.</p>

<p>The method tree then turns around and returns a boxed value again, but the compiler and runtime can again eliminate any boxing, as the method tree never deals with them in a complex way.</p>

<p>Therefore, somewhat surprisingly, the boxing to a reference style <code>java.lang.Integer</code> above can in fact be eliminated completely. The other exciting benefit is that your own value types can be treated this same way, even though (unlike <code>int</code> and <code>Integer</code>) there is no native primitive value directly representing your type. This opens a whole new opportunity for expressive and clean APIs that have to deal with primitives, closing many of the difficult &#8220;performance vs. readable&#8221; problems Java developers have faced.</p>

<h2 id='class_vs_object'>Class vs Object</h2>

<p>Several months ago I watched a presentation from Brian Goetz (can&#8217;t find the specific talk) where he discussed the potential for value objects in Java&#8217;s future, and at the time the thought was that it could be a new keyword or annotation on the type that indicated it was a value type. This proposal, however, discusses using a per-instance locking mechanism similar to:</p>
<div class='highlight'><pre><code class='java'><span class='n'>Integer</span> <span class='n'>x</span> <span class='o'>=</span> <span class='k'>new</span> <span class='n'>Integer</span><span class='o'>(</span><span class='mi'>123456</span><span class='o'>);</span>
<span class='c1'>// Not yet a value object...</span>
<span class='n'>x</span> <span class='o'>=</span> <span class='n'>x</span><span class='o'>.</span><span class='na'>lockPermanently</span><span class='o'>();</span>
<span class='c1'>// Now a value object...</span>
</code></pre>
</div>
<p>There are some benefits to this manual locking:</p>

<ul>
<li>You can use some objects as reference types; if you&#8217;re synchronizing on Integer somewhere in your code (Why?) this would allow you to continue to do so.</li>

<li>Initialization of objects that will eventually be value types can be done in multiple steps.</li>

<li>Even if your code (or some library you use) doesn&#8217;t mark the object as a value type explicitly, the JIT can still analyze the usage of the object, and transliterate it to a value type internally as a form of runtime optimization.</li>
</ul>

<p>This idea of value objects becomes a huge benefit when exploring expressive sophisticated functional programming models. Since one of the main tenants of functional programming is immutable types - if Java can in turn represent those immutable types as primitive values, it helps ensure that functional programming models don&#8217;t pay a penalty for their expressivity and immutability.</p>
  ]]></description>
</item>

	<item>
  <title>Micro Framework Plugin Architecture with Guice Multibindings</title>
  <link>http://realjenius.com/2012/01/03/guice-multibindings/</link>
  <author>R.J. Lorimer</author>
  <pubDate>2012-01-03T00:00:00-08:00</pubDate>
  <guid>http://realjenius.com/2012/01/03/guice-multibindings/</guid>
  <description><![CDATA[
     <p>Google Guice is a snazzy way to avoid all of the declarative configuration file noise and cruft, while still getting the modularity and de-coupling that you want from dependency-injection. Unlike Spring, Guice doesn&#8217;t ship with the kitchen sink. When I first picked Guice up, I wasn&#8217;t sure how (or if it was even possible out of the box) to do what I intended, which was to collect up all implementations of a particular type via injection. This is something that can be done probably in thirty five distinct ways in Spring (all of which require about fifteen XML files, if memory serves), so I was struggling to find the answer.</p>

<p>The answer, in fact, is straightforward: <strong><a href='http://code.google.com/p/google-guice/wiki/Multibindings'>Multibindings</a></strong>.</p>

<p>What is particularly neat about multi-bindings (aside from the fact they can inject a set of objects) is that they will accept bindings from multiple modules into the final aggregate set that is injected. Both sets and maps can be injected in this way. This example will use the MapBinder, as the base Guice example for Sets is fairly straightforward in its own right. Consider a music decoding application, for example. You might have simple decoder API that looks like this:</p>
<div class='highlight'><pre><code class='java'><span class='kd'>public</span> <span class='kd'>interface</span> <span class='nc'>AudioDecoder</span> <span class='o'>{</span>
    <span class='n'>String</span> <span class='nf'>getAudioTypeName</span><span class='o'>();</span>
    <span class='kt'>void</span> <span class='nf'>decode</span><span class='o'>(</span><span class='n'>InputStream</span> <span class='n'>encodedIn</span><span class='o'>,</span> <span class='n'>OutputStream</span> <span class='n'>pcmOut</span><span class='o'>);</span>
<span class='o'>}</span>
</code></pre>
</div>
<p>Individual modules can inject their own audio decoding algorithm:</p>
<div class='highlight'><pre><code class='java'><span class='kd'>public</span> <span class='kd'>class</span> <span class='nc'>Mp3AudioDecoder</span> <span class='o'>{</span>
  <span class='kd'>public</span> <span class='n'>String</span> <span class='nf'>getAudioTypeName</span><span class='o'>()</span> <span class='o'>{</span> <span class='s'>&quot;MP3&quot;</span><span class='o'>;</span> <span class='o'>}</span>
  <span class='kd'>public</span> <span class='kt'>void</span> <span class='nf'>decode</span><span class='o'>(</span><span class='n'>InputStream</span> <span class='n'>mp3In</span><span class='o'>,</span> <span class='n'>OutputStream</span> <span class='n'>pcmOut</span><span class='o'>)</span> <span class='o'>{</span>
    <span class='c1'>// Run through LAME (or similar Fraunhofer) decoding here.</span>
  <span class='o'>}</span>
<span class='o'>}</span>

<span class='c1'>// ...</span>

<span class='kd'>public</span> <span class='kd'>class</span> <span class='nc'>Mp3AudioModule</span> <span class='kd'>extends</span> <span class='n'>AbstractModule</span> <span class='o'>{</span>
  <span class='kd'>public</span> <span class='kt'>void</span> <span class='nf'>configure</span><span class='o'>()</span> <span class='o'>{</span>
    <span class='n'>Multibinder</span><span class='o'>&lt;</span><span class='n'>String</span><span class='o'>,</span><span class='n'>AudioDecoder</span><span class='o'>&gt;</span> <span class='n'>decoderBinder</span>
      <span class='o'>=</span> <span class='n'>MapBinder</span><span class='o'>.</span><span class='na'>newMapBinder</span><span class='o'>(</span><span class='n'>binder</span><span class='o'>(),</span> <span class='n'>AudioDecoder</span><span class='o'>.</span><span class='na'>class</span><span class='o'>);</span>
      <span class='n'>decoderBinder</span><span class='o'>.</span><span class='na'>addBinding</span><span class='o'>(</span><span class='s'>&quot;mp3&quot;</span><span class='o'>).</span><span class='na'>to</span><span class='o'>(</span><span class='n'>Mp3AudioDecoder</span><span class='o'>.</span><span class='na'>class</span><span class='o'>);</span>
  <span class='o'>}</span>
<span class='o'>}</span>
</code></pre>
</div>
<p>What this does is register a binding with the multibinder from <code>AudioDecoder</code> to <code>Mp3AudioDecoder</code>; effectively registering that type as part of the total set of audio decoders. Consuming these via injection requires no special sauce; simply declaring you want to receive the map is all that is required:</p>
<div class='highlight'><pre><code class='java'><span class='kd'>public</span> <span class='kd'>class</span> <span class='nc'>RootModule</span> <span class='kd'>extends</span> <span class='n'>AbstractModule</span> <span class='o'>{</span>
  <span class='kd'>public</span> <span class='kt'>void</span> <span class='nf'>configure</span><span class='o'>()</span> <span class='o'>{</span>
    <span class='n'>bind</span><span class='o'>(</span><span class='n'>AudioDecodingThingy</span><span class='o'>.</span><span class='na'>class</span><span class='o'>);</span>
  <span class='o'>}</span>
<span class='o'>}</span>
        
<span class='kd'>public</span> <span class='kd'>class</span> <span class='nc'>AudioDecodingThingy</span> <span class='o'>{</span>

  <span class='kd'>private</span> <span class='kd'>final</span> <span class='n'>Map</span><span class='o'>&lt;</span><span class='n'>String</span><span class='o'>,</span><span class='n'>AudioDecoder</span><span class='o'>&gt;</span> <span class='n'>decoders</span><span class='o'>;</span>
    
  <span class='nd'>@Inject</span>
  <span class='kd'>public</span> <span class='nf'>AudioDecodingThingy</span><span class='o'>(</span><span class='n'>Map</span><span class='o'>&lt;</span><span class='n'>String</span><span class='o'>,</span><span class='n'>AudioDecoder</span><span class='o'>&gt;</span> <span class='n'>decoders</span><span class='o'>)</span> <span class='o'>{</span>
    <span class='k'>this</span><span class='o'>.</span><span class='na'>decoders</span> <span class='o'>=</span> <span class='n'>decoders</span><span class='o'>;</span>
  <span class='o'>}</span>

  <span class='kd'>public</span> <span class='kt'>void</span> <span class='nf'>run</span><span class='o'>(</span><span class='n'>String</span> <span class='n'>inputFile</span><span class='o'>,</span> <span class='n'>String</span> <span class='n'>outputFile</span><span class='o'>)</span> <span class='o'>{</span>
    <span class='c1'>// Basic error handling.</span>
    <span class='n'>File</span> <span class='n'>in</span> <span class='o'>=</span> <span class='k'>new</span> <span class='n'>File</span><span class='o'>(</span><span class='n'>inputFile</span><span class='o'>);</span>
    <span class='n'>File</span> <span class='n'>out</span> <span class='o'>=</span> <span class='k'>new</span> <span class='n'>File</span><span class='o'>(</span><span class='n'>outputFile</span><span class='o'>);</span>
    <span class='n'>String</span> <span class='n'>extension</span> <span class='o'>=</span> <span class='n'>getExtension</span><span class='o'>(</span><span class='n'>inputFile</span><span class='o'>);</span>

    <span class='k'>if</span><span class='o'>(!</span><span class='n'>in</span><span class='o'>.</span><span class='na'>exists</span><span class='o'>())</span> <span class='k'>throw</span> <span class='k'>new</span> <span class='n'>IllegalArgumentException</span><span class='o'>(</span><span class='s'>&quot;File &quot;</span> <span class='o'>+</span> <span class='n'>inputFile</span> <span class='o'>+</span> <span class='s'>&quot; not found.&quot;</span><span class='o'>);</span>
    <span class='k'>if</span><span class='o'>(!</span><span class='n'>decoders</span><span class='o'>.</span><span class='na'>containsKey</span><span class='o'>(</span><span class='n'>extension</span><span class='o'>))</span> <span class='k'>throw</span> <span class='k'>new</span> <span class='n'>IllegalArgumentException</span><span class='o'>(</span><span class='s'>&quot;No decoder found for extension: &quot;</span> <span class='o'>+</span> <span class='n'>extension</span><span class='o'>);</span>
    <span class='k'>if</span><span class='o'>(!</span><span class='n'>out</span><span class='o'>.</span><span class='na'>exists</span><span class='o'>()</span> <span class='o'>&amp;&amp;</span> <span class='o'>!</span><span class='n'>out</span><span class='o'>.</span><span class='na'>createNewFile</span><span class='o'>())</span> <span class='k'>throw</span> <span class='k'>new</span> <span class='n'>IllegalArgumentException</span><span class='o'>(</span><span class='s'>&quot;Unable to create output file: &quot;</span> <span class='o'>+</span> <span class='n'>outputFile</span><span class='o'>);</span>

    <span class='n'>AudioDecoder</span> <span class='n'>decoder</span> <span class='o'>=</span> <span class='n'>decoders</span><span class='o'>.</span><span class='na'>get</span><span class='o'>(</span><span class='n'>extension</span><span class='o'>);</span>

    <span class='c1'>// Do the decoding.</span>
    <span class='k'>try</span><span class='o'>(</span>
      <span class='n'>InputStream</span> <span class='n'>in</span> <span class='o'>=</span> <span class='k'>new</span> <span class='n'>FileInputStream</span><span class='o'>(</span><span class='n'>in</span><span class='o'>);</span>
      <span class='n'>OutputStream</span> <span class='n'>out</span> <span class='o'>=</span> <span class='k'>new</span> <span class='n'>FileOutputStream</span><span class='o'>(</span><span class='n'>out</span><span class='o'>))</span> <span class='o'>{</span>
        <span class='n'>decoder</span><span class='o'>.</span><span class='na'>decode</span><span class='o'>(</span><span class='n'>in</span><span class='o'>,</span> <span class='n'>out</span><span class='o'>);</span>
    <span class='o'>}</span>
  <span class='o'>}</span>
<span class='o'>}</span>
        
<span class='kd'>public</span> <span class='kd'>class</span> <span class='nc'>Main</span> <span class='o'>{</span>
  <span class='kd'>public</span> <span class='kd'>static</span> <span class='kt'>void</span> <span class='nf'>main</span><span class='o'>(</span><span class='n'>String</span><span class='o'>[]</span> <span class='n'>args</span><span class='o'>)</span> <span class='o'>{</span>
    <span class='n'>Injector</span> <span class='n'>i</span> <span class='o'>=</span> <span class='n'>Guice</span><span class='o'>.</span><span class='na'>createInjector</span><span class='o'>(</span>
      <span class='k'>new</span> <span class='nf'>RootModule</span><span class='o'>(),</span> <span class='k'>new</span> <span class='n'>Mp3Module</span><span class='o'>(),</span> <span class='k'>new</span> <span class='n'>OggModule</span><span class='o'>());</span>

    <span class='n'>AudioDecodingThingy</span> <span class='n'>thingy</span>
      <span class='o'>=</span> <span class='n'>i</span><span class='o'>.</span><span class='na'>getInstance</span><span class='o'>(</span><span class='n'>AudioDecodingThingy</span><span class='o'>.</span><span class='na'>class</span><span class='o'>);</span>

    <span class='n'>thingy</span><span class='o'>.</span><span class='na'>run</span><span class='o'>(</span><span class='n'>args</span><span class='o'>[</span><span class='mi'>0</span><span class='o'>],</span> <span class='n'>args</span><span class='o'>[</span><span class='mi'>1</span><span class='o'>]);</span>
  <span class='o'>}</span>
<span class='o'>}</span>
</code></pre>
</div>
<p>While this particular example (and the example on the Guice site) have the modules to snap-in defined directly in the code, it is not a stretch of the imagination to envision the possible modules to install coming from:</p>

<ul>
<li>A configuration file</li>

<li>The built-in JAR service-provider and ServiceLoader facilities.</li>

<li>A scan for all particular annotated types; something like <code>@PluginModule</code></li>
</ul>

<p>As a final disclaimer (one that is reiterated on the Guice site) Multibindings are not a replacement for a full modular architecture, like that which can be achieved with OSGi (in fact, Guice has <a href='http://code.google.com/p/google-guice/wiki/OSGi'>support for OSGi</a> as well). However, sometimes OSGi can be a power-drill, when sometimes all you need is a plain ol&#8217; screwdriver.</p>

<p>Multibindings, which are an extension to Guice, are shipped as a separate integration JAR file. All of the official extensions are <a href='http://mvnrepository.com/artifact/com.google.inject.extensions'>available in the core Maven repositories</a> under <code>com.google.inject.extensions</code>.</p>
  ]]></description>
</item>

	<item>
  <title>Google Guava and Multimaps</title>
  <link>http://realjenius.com/2011/12/22/guava-multimaps/</link>
  <author>R.J. Lorimer</author>
  <pubDate>2011-12-22T00:00:00-08:00</pubDate>
  <guid>http://realjenius.com/2011/12/22/guava-multimaps/</guid>
  <description><![CDATA[
     <p>It&#8217;s not uncommon in Java to build some sort of in-memory registry that contains a map with a list of items at each position. Often, these implementations look something like this (excluding concurrency details for brevity):</p>
<div class='highlight'><pre><code class='java'><span class='kd'>private</span> <span class='n'>Map</span><span class='o'>&lt;</span><span class='n'>String</span><span class='o'>,</span><span class='n'>List</span><span class='o'>&lt;</span><span class='n'>Something</span><span class='o'>&gt;&gt;</span> <span class='n'>stuff</span> <span class='o'>=</span> <span class='k'>new</span> <span class='n'>HashMap</span><span class='o'>&lt;</span><span class='n'>String</span><span class='o'>,</span><span class='n'>List</span><span class='o'>&lt;</span><span class='n'>Something</span><span class='o'>&gt;&gt;();</span>

<span class='c1'>// ...</span>

<span class='kd'>public</span> <span class='kt'>void</span> <span class='nf'>add</span><span class='o'>(</span><span class='n'>String</span> <span class='n'>key</span><span class='o'>,</span> <span class='n'>Something</span> <span class='n'>item</span><span class='o'>)</span> <span class='o'>{</span>
  <span class='k'>if</span><span class='o'>(!</span><span class='n'>stuff</span><span class='o'>.</span><span class='na'>containsKey</span><span class='o'>(</span><span class='n'>key</span><span class='o'>))</span> <span class='o'>{</span>
    <span class='n'>stuff</span><span class='o'>.</span><span class='na'>put</span><span class='o'>(</span><span class='n'>key</span><span class='o'>,</span> <span class='k'>new</span> <span class='n'>ArrayList</span><span class='o'>&lt;</span><span class='n'>Something</span><span class='o'>&gt;());</span>
  <span class='o'>}</span>
  <span class='n'>stuff</span><span class='o'>.</span><span class='na'>get</span><span class='o'>(</span><span class='n'>key</span><span class='o'>).</span><span class='na'>add</span><span class='o'>(</span><span class='n'>item</span><span class='o'>);</span>
<span class='o'>}</span>

<span class='kd'>public</span> <span class='n'>List</span><span class='o'>&lt;</span><span class='n'>Something</span><span class='o'>&gt;</span> <span class='n'>get</span><span class='o'>(</span><span class='n'>String</span> <span class='n'>key</span><span class='o'>)</span> <span class='o'>{</span>
  <span class='k'>return</span> <span class='k'>new</span> <span class='n'>ArrayList</span><span class='o'>&lt;</span><span class='n'>Something</span><span class='o'>&gt;(</span><span class='n'>stuff</span><span class='o'>.</span><span class='na'>get</span><span class='o'>(</span><span class='n'>key</span><span class='o'>));</span>
<span class='o'>}</span>
</code></pre>
</div>
<p><a href='http://guava-libraries.googlecode.com'>Google&#8217;s Guava Libraries</a> provide a few collections to help with this common case: <code>com.google.common.collect.Multimap</code>, and the more specific variants <code>ListMultimap</code>, <code>SetMultimap</code>, and <code>SortedSetMultimap</code>.</p>

<p>The above code can be re-written with Guava like this:</p>
<div class='highlight'><pre><code class='java'><span class='kd'>private</span> <span class='n'>ListMultimap</span><span class='o'>&lt;</span><span class='n'>String</span><span class='o'>,</span><span class='n'>Something</span><span class='o'>&gt;</span> <span class='n'>stuff</span> <span class='o'>=</span> <span class='n'>ArrayListMultimap</span><span class='o'>.</span><span class='na'>create</span><span class='o'>();</span>

<span class='c1'>// ...</span>

<span class='kd'>public</span> <span class='kt'>void</span> <span class='nf'>add</span><span class='o'>(</span><span class='n'>String</span> <span class='n'>key</span><span class='o'>,</span> <span class='n'>Something</span> <span class='n'>item</span><span class='o'>)</span> <span class='o'>{</span>
  <span class='n'>stuff</span><span class='o'>.</span><span class='na'>put</span><span class='o'>(</span><span class='n'>key</span><span class='o'>,</span> <span class='n'>item</span><span class='o'>);</span>
<span class='o'>}</span>

<span class='kd'>public</span> <span class='n'>List</span><span class='o'>&lt;</span><span class='n'>Something</span><span class='o'>&gt;</span> <span class='n'>get</span><span class='o'>(</span><span class='n'>String</span> <span class='n'>key</span><span class='o'>)</span> <span class='o'>{</span>
  <span class='c1'>// might as well use the Lists convenience API while we&#39;re at it.</span>
  <span class='k'>return</span> <span class='n'>Lists</span><span class='o'>.</span><span class='na'>newArrayList</span><span class='o'>(</span><span class='n'>stuff</span><span class='o'>.</span><span class='na'>get</span><span class='o'>(</span><span class='n'>key</span><span class='o'>));</span>
<span class='o'>}</span>
</code></pre>
</div>
<p>The multi-map has a variety of fancy features that can be used as well. Here are just a few examples:</p>
<div class='highlight'><pre><code class='java'><span class='c1'>// returns a composite of all values from all entries.</span>
<span class='n'>Collection</span><span class='o'>&lt;</span><span class='n'>Something</span><span class='o'>&gt;</span> <span class='n'>allSomethings</span> <span class='o'>=</span> <span class='n'>stuff</span><span class='o'>.</span><span class='na'>values</span><span class='o'>();</span> 

<span class='c1'>// A more traditional map that can be edited.</span>
<span class='n'>Map</span><span class='o'>&lt;</span><span class='n'>String</span><span class='o'>,</span> <span class='n'>Collection</span><span class='o'>&lt;</span><span class='n'>Something</span><span class='o'>&gt;&gt;</span> <span class='n'>mapView</span> <span class='o'>=</span> <span class='n'>stuff</span><span class='o'>.</span><span class='na'>asMap</span><span class='o'>();</span>

<span class='c1'>// remove an individual entry for a key.</span>
<span class='kt'>boolean</span> <span class='n'>removed</span> <span class='o'>=</span> <span class='n'>stuff</span><span class='o'>.</span><span class='na'>remove</span><span class='o'>(</span><span class='n'>key</span><span class='o'>,</span> <span class='n'>someVal</span><span class='o'>);</span>

<span class='c1'>// remove all for a key</span>
<span class='n'>List</span><span class='o'>&lt;</span><span class='n'>Something</span><span class='o'>&gt;</span> <span class='n'>removedSomethings</span> <span class='o'>=</span> <span class='n'>stuff</span><span class='o'>.</span><span class='na'>remove</span><span class='o'>(</span><span class='n'>key</span><span class='o'>);</span>

<span class='c1'>// One for each value in the map. Updating this collection updates the map.</span>
<span class='n'>Collection</span><span class='o'>&lt;</span><span class='n'>Map</span><span class='o'>.</span><span class='na'>Entry</span><span class='o'>&lt;</span><span class='n'>String</span><span class='o'>,</span><span class='n'>Something</span><span class='o'>&gt;&gt;</span> <span class='n'>allEntries</span> <span class='o'>=</span> <span class='n'>stuff</span><span class='o'>.</span><span class='na'>entries</span><span class='o'>();</span>
</code></pre>
</div>
<p>All of the collections returned by the various API are views of the multimap. This can make it particularly easy to work with the map in a variety of ways. It does mean you should probably perform defensive copying anywhere you might be exposing these APIs (generally good practice in most cases, anyway).</p>
  ]]></description>
</item>

	<item>
  <title>Spark: Sinatra Goes Verbose</title>
  <link>http://realjenius.com/2011/08/02/spark-sinatra-goes-verbose/</link>
  <author>R.J. Lorimer</author>
  <pubDate>2011-08-02T00:00:00-07:00</pubDate>
  <guid>http://realjenius.com/2011/08/02/spark-sinatra-goes-verbose/</guid>
  <description><![CDATA[
     <p>It would seem that the prevailing wisdom in the upper echelon of alpha-geeks is that Java, as a language, is no longer generally viable for effective coding of&#8230; well frankly, anything. Where-as five years ago, everyone working on the JVM was looking for the next-best-Java-framework, it seems the focus has switched to finding the next-best-language instead. Scala, JRuby, Clojure, Groovy, and a whole host of other JVM-based languages (there are several new contenders like Kotlin, Ceylon, Stab, Gosu, and Mirah) have begun making news for their vastly superior language features that promise to dramatically improve the coding experience, and ideally, improve the code itself.</p>

<p>It&#8217;s no surprise Java developers are trying to branch out: Java 7, which was nearly five years in the making, barely evolves the language features at all; most of the promised game-changers for the language (lambdas, extension methods, modules) were deferred to Java 8 due to lack of consensus and time. Java has become stagnant, too verbose, and too crufty for developers that have seen the greener grass on the other side.</p>

<p>Unfortunately, most JVM developers in the wild are still using the Java language in some capacity, and it seems to be fairly common in companies that there is a distinct reason that an alternative VM language hasn&#8217;t been adopted in its place. The reasons may not satiate the idealists of the JVM-based community, but they do exist. Just to name a few:</p>

<ul>
<li>Corporate restrictions</li>

<li>Concerns about code maintainability</li>

<li>Team skill-sets and strengths</li>

<li>Stability and performance of the various language platform</li>

<li>Lack of top-grade IDE support</li>
</ul>

<p>Frameworks, on the other hand, often seem to be an easier pill to swallow. The barrier to entry for developers is often lower, the scope of impact on your application can be less pervasive, and your tools and team skill-sets are not stretched nearly so far. In reality, some frameworks (<em>cough</em>Spring<em>cough</em>) actually add more complexity than any language shift would, but this is unfortunately a game of perception. As it pertains to frameworks in the post-Java JVM world, those of you that follow my blog or Twitter account know that I&#8217;m a big fan of the <a href='http://www.playframework.org'>Play! Framework</a>, as it re-imagined what it means to write a Java web application, and it also provides an easy gateway into Scala. It shows that while Java the language is falling behind, it isn&#8217;t a complete wasteland for developers craving more.</p>

<p>A co-worker recently pointed out another intriguing Java framework that, while not being as full-featured or targeted for large applications as Play!, has a lot to offer to this neo-Java world: enter <a href='http://www.sparkjava.com/'>Spark</a>.</p>

<p>Those of you who have worked with (or at least seen) Ruby&#8217;s <a href='http://www.sinatrarb.com/'>Sinatra framework</a> will instantly feel home (and perhaps vaguely disgruntled) with Spark. Spark is effectively the Sinatra-style of web-binding, using Java syntax. Here is an example from their home-page:</p>
<div class='highlight'><pre><code class='java'><span class='kn'>import</span> <span class='nn'>static</span> <span class='n'>spark</span><span class='o'>.</span><span class='na'>Spark</span><span class='o'>.*;</span>
<span class='kn'>import</span> <span class='nn'>spark.*</span><span class='o'>;</span>

<span class='kd'>public</span> <span class='kd'>class</span> <span class='nc'>HelloWorld</span> <span class='o'>{</span>

   <span class='kd'>public</span> <span class='kd'>static</span> <span class='kt'>void</span> <span class='nf'>main</span><span class='o'>(</span><span class='n'>String</span><span class='o'>[]</span> <span class='n'>args</span><span class='o'>)</span> <span class='o'>{</span>
      
      <span class='n'>get</span><span class='o'>(</span><span class='k'>new</span> <span class='n'>Route</span><span class='o'>(</span><span class='s'>&quot;/hello&quot;</span><span class='o'>)</span> <span class='o'>{</span>
         <span class='nd'>@Override</span>
         <span class='kd'>public</span> <span class='n'>Object</span> <span class='nf'>handle</span><span class='o'>(</span><span class='n'>Request</span> <span class='n'>request</span><span class='o'>,</span> <span class='n'>Response</span> <span class='n'>response</span><span class='o'>)</span> <span class='o'>{</span>
            <span class='k'>return</span> <span class='s'>&quot;Hello World!&quot;</span><span class='o'>;</span>
         <span class='o'>}</span>
      <span class='o'>});</span>

   <span class='o'>}</span>

<span class='o'>}</span>
</code></pre>
</div>
<p>The general idea behind Spark is to make the binding between a URL to the actual code being run as thin as possible - allowing you to focus on servicing the request. When compared to many frameworks, the list of features it <em>doesn&#8217;t</em> have may be disconcerting; but, there is a certain power and portability in the simplicity. The self-coined term &#8220;micro-web-framework&#8221; is really only true due to the sheer volume of complexity and features that Java web frameworks have decided to provide (or impose) in the last few years.</p>

<p>Like Play!, Spark focuses on using very human-readable API design. The central component of Spark is the callback which handles the request. As seen in the above example, this is provided by the developer via a subclass of &#8220;Route&#8221;. What happens inside the callback to build the result is entirely up to you.</p>

<p>While Spark doesn&#8217;t get involved in the &#8220;manipulating data&#8221; part, there are a handful of features and utilities available to help with the control of HTTP-level web-flow. Some of these include:</p>

<ul>
<li>Filters - These are callbacks just like the routes that can be run based on certain URL patterns, allowing for functionality to be applied orthogonal to a set of requests.</li>

<li>Request/Response Wrappers - The servlet request and response classes are well known (and often loathed) for their design. Spark, like many frameworks, wraps these to help conceal the suck.</li>

<li>Halt Commands - This is an increasingly popular API design in web frameworks: methods that set an HTTP status code, and fail with an exception immediately.</li>

<li>Redirects - Browser redirects are made particularly simple.</li>
</ul>

<p>All of these features are shown in more detail on the <a href='http://www.sparkjava.com/readme.html'>Spark Readme Page</a>.</p>

<p>Spark&#8217;s main facility for running is to start up an embedded Jetty server to automatically handle requests. This is right in-line with how Sinatra functions by default, and provides a quick and easy process for developers to get their application going to test and do development. While not documented on the site, Spark does support a deployed mode where it can be run inside of an already-deployed application server as a WAR with a web.xml file. This is done via the spark.servlet.SparkFilter class, which is a servlet filter that can route requests to your application.</p>

<p>In summary: it&#8217;s unlikely you would want to implement your entire enterprise on Spark, but that&#8217;s not really its goal. Spark is really targeted for quick-to-live &#8220;scrapplications&#8221;; getting something together in a short amount of time, and in the hands of users, without the pomp and circumstance of importing 900 JARs, and creating 35 configuration files. It explicitly avoids imposing a particular application model, data model, or really any dependencies at all on the developer, instead offering a small expressive Java API (as expressive as Java gets anyway), that allows you to quickly map blocks of Java code to RESTful HTTP routes. Overall - definitely worth checking out.</p>
  ]]></description>
</item>

	<item>
  <title>Review: "Apache Wicket Cookbook"</title>
  <link>http://realjenius.com/2011/05/07/review-apache-wicket-cookbook/</link>
  <author>R.J. Lorimer</author>
  <pubDate>2011-05-07T00:00:00-07:00</pubDate>
  <guid>http://realjenius.com/2011/05/07/review-apache-wicket-cookbook/</guid>
  <description><![CDATA[
     <div class='thumbnail pull-right'>
	<img src='http://realjenius.com/images/articles/misc/Apache-Wicket.png' />
	
</div>
<p>Earlier this week, the folks over at <a href='http://www.packtpub.com/'>Packt Publishing</a> were kind enough to forward me a copy of the <strong><a href='http://link.packtpub.com/D58AdD'>Apache Wicket Cookbook</a></strong> for review, and given my previous positive experiences with <a href='http://wicket.apache.org/'>Wicket</a>, I was excited to dive in, and see what the book has to offer.</p>

<h2 id='overview'>Overview</h2>

<p><a href='http://link.packtpub.com/D58AdD'>Apache Wicket Cookbook</a> is a dense collection of recipes for working with the various Wicket features, and is written by Igor Vaynberg, one of the main Wicket committers, who is also a contributing author to <a href='http://wicketinaction.com/'>Wicket in Action</a>. While &#8220;Wicket in Action&#8221; is targeted at understanding the &#8220;what and why&#8221; of Wicket, this new cookbook is all about the &#8220;how&#8221;. To re-summarize from the preface of the book itself:</p>

<blockquote>
<p>A straightforward Cookbook with over 70 highly focused practical recipes to make your web application development easier with the Wicket web framework.</p>
</blockquote>

<p>The book is composed in a repeating format, showing different solutions to problems using the same rough outline for each recipe:</p>

<ul>
<li>Overview - To start each recipe, a short introductory set of paragraphs are provided that explain the problem at hand, and why it might be important to have a solution.</li>

<li>Getting Ready - This section sets up the example for the recipe, providing the necessary code snippets to try the recipe out for yourself.</li>

<li>How to do it - After prepping the example, this section jumps right in with highlighted code changes, showing how to solve this particular problem with Wicket.</li>

<li>How it works - Now that the reader has seen what to do to fix the problem, this section explains how Wicket uses the code provided to handle the particular problem, and provides more detail for people who like to understand what&#8217;s going on under the covers.</li>

<li>There&#8217;s more - Because these examples are so focused, they don&#8217;t touch on all facets of a particular API. This section provides highlights of other features to explore on your own.</li>

<li>See also - A lot of the recipes are inter-related, solving similar, but different problems. This section points you to other recipes in the book that compliment the one you just read.</li>
</ul>

<h2 id='review'>Review</h2>

<p>Overall, I&#8217;ve been quite impressed with the &#8220;Apache Wicket Cookbook&#8221;. Having been quite familiar with Wicket over the years from writing a number of tutorial articles about it, and applications with it, I found the previously released &#8220;Wicket in Action&#8221; to be a bit of a redundant read; most of the code and APIs were familiar enough to me in concept, that I didn&#8217;t feel that book was the right target for me. This book, on the other hand, is very no-nonsense, and hits on a lot of detailed problems that even a seasoned &#8220;Wicketeer&#8221; would probably have to really dig to solve in a novel and clean way.</p>

<p>This book touches on many of the &#8220;hard&#8221; problems, including:</p>

<ul>
<li>The nuances of safe, attractive, and error-free form handling - the web is all about this, of course, but it seems like most people don&#8217;t do it right. Wicket has the tools, but you&#8217;ve got to know how to apply them - and there are enough recipes here to train your brain!</li>

<li>Internationalization - Who hasn&#8217;t struggled with this in one fashion or another?</li>

<li>Data Tables - Paging, Sorting, Filtering tables are another &#8220;hard to implement&#8221; cornerstone of the web, and an area where Wicket really shines.</li>

<li>Security - Wicket&#8217;s security model is intense; that&#8217;s both good and bad, and this section really hits on some sticky (get it? Sticky wicket?) topics, like cross-site request forgery protection.</li>
</ul>

<p>Other topics touched on by the book include AJAX and Rich UIs (another Wicket &#8220;wow&#8221; feature), middleware integration (e.g. Spring), and, interestingly enough, charting and graphing.</p>

<p>Being very familiar with Wicket, I didn&#8217;t feel the need to try most of these examples for myself, and so despite the book being over 300 pages in ebook form, I found myself finishing my read-through in short order. I wouldn&#8217;t say the book is short, but for me, it was over quickly.</p>

<p>Some of the sections, like the aforementioned chapter on charting, were new to me, and gave me a better feel of how this book would be received by someone less familiar. Others covered problems I have previously solved myself with Wicket, and I was happy to see solutions that I felt were both cleaner and more complete than the solutions I had &#8220;cooked up&#8221; myself.</p>

<p>Most of the examples are based in reality; not having the overly contrived feel of an author searching for a problem to solve; and many of the chapters focus on a particular example, and build upon it in several stages - providing a good picture on how to take a bare implementation and layer on features until it is &#8220;complete&#8221;.</p>

<p>If you are already familiar with Wicket, but would like to better understand how to use it effectively to build robust, feature-rich, and pretty applications, then this book is for you.</p>

<p>On the other hand, if you&#8217;ve never used Wicket before, you will be lost the moment you hit the first chapter. It just so happens, that <a href='http://wicketinaction.com/book/'>Wicket in Action</a> is already available for novices, as are a <a href='http://www.google.com/search?sourceid=chrome&amp;ie=UTF-8&amp;q=wicket+tutorial'>number of online resources</a> (some by yours truly; albeit a little out of date).</p>

<p>For those of you that would like to try this new book out, I have been given access to a free chapter that you can download in PDF format: <strong><a href='http://www.packtpub.com/sites/default/files/1605OS-Chapter-5-Displaying-Data-Using-DataTable.pdf?utm_source=packtpub&amp;utm_medium=free&amp;utm_campaign=pdf'>Chapter 5: Displaying Data Using DataTable</a></strong>.</p>
  ]]></description>
</item>

	<item>
  <title>The Folly of Try-With-Resources in Java 7</title>
  <link>http://realjenius.com/2011/01/23/the-folly-of-try-with-resources/</link>
  <author>R.J. Lorimer</author>
  <pubDate>2011-01-23T00:00:00-08:00</pubDate>
  <guid>http://realjenius.com/2011/01/23/the-folly-of-try-with-resources/</guid>
  <description><![CDATA[
     <p>Java 7, which is slated to be released ninety years ago, is supposed to add a feature as part of the <a href='http://openjdk.java.net/projects/coin/'>Project Coin initiative</a> called &#8220;try-with-resources&#8221;. The idea is fairly simple, and is intended to tidy up a common development problem in Java: the safe life-cycle management of volatile resources.</p>

<p>In concept I have no problem with this sort of support. There are innumerable examples on the web of absurd Java try/catch/finally block hierarchies to properly managing input streams and output streams; something that is the norm, not the exception to the rule.</p>
<div class='highlight'><pre><code class='java'><span class='n'>InputStream</span> <span class='n'>in</span><span class='o'>;</span>
<span class='k'>try</span> <span class='o'>{</span>
  <span class='n'>in</span> <span class='o'>=</span> <span class='n'>loadInput</span><span class='o'>(...);</span>
    <span class='n'>OutputStream</span> <span class='n'>out</span><span class='o'>;</span>
  <span class='k'>try</span> <span class='o'>{</span>
    <span class='n'>out</span> <span class='o'>=</span> <span class='n'>createOutput</span><span class='o'>(...);</span>
    <span class='n'>copy</span><span class='o'>(</span><span class='n'>in</span><span class='o'>,</span> <span class='n'>out</span><span class='o'>);</span>
  <span class='o'>}</span>
  <span class='k'>finally</span> <span class='o'>{</span>
    <span class='k'>if</span><span class='o'>(</span><span class='n'>out</span> <span class='o'>!=</span> <span class='kc'>null</span><span class='o'>)</span> <span class='o'>{</span>
      <span class='k'>try</span> <span class='o'>{</span>
        <span class='n'>out</span><span class='o'>.</span><span class='na'>close</span><span class='o'>();</span>
      <span class='o'>}</span>
      <span class='k'>catch</span><span class='o'>(</span><span class='n'>IOException</span> <span class='n'>ioe</span><span class='o'>)</span> <span class='o'>{</span>
        <span class='c1'>// Problem closing the output stream.</span>
      <span class='o'>}</span>
    <span class='o'>}</span>
  <span class='o'>}</span>
<span class='o'>}</span>
<span class='k'>catch</span><span class='o'>(</span><span class='n'>IOException</span> <span class='n'>e</span><span class='o'>)</span> <span class='o'>{</span>
  <span class='c1'>// Problem reading or writing with streams.</span>
  <span class='c1'>// Or problem opening one of them.</span>
<span class='o'>}</span>
<span class='k'>finally</span> <span class='o'>{</span>
  <span class='k'>if</span><span class='o'>(</span><span class='n'>in</span> <span class='o'>!=</span> <span class='kc'>null</span><span class='o'>)</span> <span class='o'>{</span>
    <span class='k'>try</span> <span class='o'>{</span>
      <span class='n'>in</span><span class='o'>.</span><span class='na'>close</span><span class='o'>();</span>
    <span class='o'>}</span>
    <span class='k'>catch</span><span class='o'>(</span><span class='n'>IOException</span> <span class='n'>ioe</span><span class='o'>)</span> <span class='o'>{</span>
      <span class='c1'>// Problem closing the input stream.</span>
    <span class='o'>}</span>
  <span class='o'>}</span>
<span class='o'>}</span>
</code></pre>
</div>
<p>I&#8217;m not even showing here how you handle the situation where reading/writing caused an error, <strong>and</strong> closing one or both of the streams caused an error. You want a way to cleanly collect all of these up into one exception bundle that can be properly logged/handled, but short of rolling your own wrapper exception to potentially hold all conditions, there simply is no way.</p>

<p>This abhorrent pile of braces can be cleanly tightened up with the new facilities in Java 7 like so:</p>
<div class='highlight'><pre><code class='java'><span class='k'>try</span> <span class='o'>(</span><span class='n'>InputStream</span> <span class='n'>in</span> <span class='o'>=</span> <span class='n'>loadInput</span><span class='o'>(...);</span> 
     <span class='n'>OutputStream</span> <span class='n'>out</span> <span class='o'>=</span> <span class='n'>createOutput</span><span class='o'>(...)</span> <span class='o'>){</span>
  <span class='n'>copy</span><span class='o'>(</span><span class='n'>in</span><span class='o'>,</span> <span class='n'>out</span><span class='o'>);</span>
<span class='o'>}</span>
<span class='k'>catch</span> <span class='o'>(</span><span class='n'>Exception</span> <span class='n'>e</span><span class='o'>)</span> <span class='o'>{</span>
  <span class='c1'>// Problem reading and writing streams.</span>
  <span class='c1'>// Or problem opening one of them.</span>
  <span class='c1'>// If compound error closing streams occurs, it will be recorded on this exception </span>
  <span class='c1'>// as a &quot;suppressedException&quot;.</span>
<span class='o'>}</span>
</code></pre>
</div>
<p>Java will know how to close items in the try parenthesis by those elements implementing the &#8220;AutoCloseable&#8221; interface. This is much like the &#8220;Iterable&#8221; interface that was added to support the enhanced-for loops in Java 5. Clearly this code is much cleaner, and automatic resource management is a facility that Java has needed (for a <em>lonnnnnngg</em> time) - so why am I miffed?</p>

<p>This feature, which is consuming a non-trivial amount of draft specification time and development time to get right, is being implemented as a language feature via the use of compiler changes - again, much in the same way as enhanced-for was implemented. For the record, I was miffed about enhanced-for as well (although I do use it regularly).</p>

<p>Adding this as a language feature, rather than a library feature, bloats the compiler specification and implementation, and completely hides the real implementation in generated code. It&#8217;s functional to a point, but is not extensible by developers. Sadly, none of this would be necessary at all if Java 7 shipped with lambda/closure support, and I think the syntax is more natural. Here is a naive Ruby file copy/transform algorithm.</p>
<div class='highlight'><pre><code class='java'><span class='n'>begin</span>
  <span class='n'>File</span><span class='o'>.</span><span class='na'>open</span><span class='o'>(</span><span class='s'>&quot;myInput.txt&quot;</span><span class='o'>,</span> <span class='s'>&quot;r&quot;</span><span class='o'>)</span> <span class='k'>do</span> <span class='o'>|</span><span class='n'>in</span><span class='o'>|</span>
    <span class='n'>File</span><span class='o'>.</span><span class='na'>open</span><span class='o'>(</span><span class='s'>&quot;myOutput.txt&quot;</span><span class='o'>,</span> <span class='s'>&quot;w&quot;</span><span class='o'>)</span> <span class='k'>do</span> <span class='o'>|</span><span class='n'>out</span><span class='o'>|</span>
      <span class='n'>in</span><span class='o'>.</span><span class='na'>each_line</span> <span class='k'>do</span> <span class='o'>|</span><span class='n'>line</span><span class='o'>|</span>
        <span class='n'>out</span> <span class='o'>&lt;&lt;</span> <span class='n'>line</span><span class='o'>.</span><span class='na'>upcase</span> <span class='o'>&lt;&lt;</span> <span class='s'>&quot;\n&quot;</span>
      <span class='n'>end</span>
    <span class='n'>end</span>
  <span class='n'>end</span>
<span class='n'>rescue</span> <span class='n'>exc</span>
  <span class='err'>#</span> <span class='n'>Exception</span> <span class='n'>occurred</span> <span class='n'>reading</span><span class='o'>/</span><span class='n'>writing</span><span class='o'>!</span>
<span class='n'>end</span>
</code></pre>
</div>
<p>Now, admittedly the syntax is very different than the Java version - the most notable difference is that the Ruby version is actual three nested lambas, where as the Java version is sort-of two lambdas (one to open the resources, one to work with them). I say sort-of, because the first is this special quasi-code-block that also magically accumulates opened resources for later closure.</p>

<p>I find the lambda version to be much less hand-wavy - the syntax is naturally intuitive and more flexible. I should also note that the inner-most lambda, which iterates over lines in the file, shows that the enhanced for loop in Java is completely unnecessary as well if you have lambdas.</p>

<p>Using one of the proposed syntaxes for Java lambda support (as ugly as they can be), let&#8217;s take a shot at this same idea with Java:</p>
<div class='highlight'><pre><code class='java'><span class='k'>try</span> <span class='o'>{</span>
  <span class='n'>File</span><span class='o'>.</span><span class='na'>read</span><span class='o'>(</span><span class='s'>&quot;myInput.txt&quot;</span><span class='o'>,</span> <span class='o'>{</span> <span class='n'>in</span> <span class='o'>-&gt;</span>
    <span class='n'>File</span><span class='o'>.</span><span class='na'>write</span><span class='o'>(</span><span class='s'>&quot;myOutput.txt&quot;</span><span class='o'>,</span> <span class='o'>{</span> <span class='n'>out</span> <span class='o'>-&gt;</span>
      <span class='n'>in</span><span class='o'>.</span><span class='na'>eachLine</span><span class='o'>(</span> <span class='o'>{</span> <span class='n'>line</span> <span class='o'>-&gt;</span>
        <span class='n'>out</span><span class='o'>.</span><span class='na'>write</span><span class='o'>(</span><span class='n'>line</span><span class='o'>.</span><span class='na'>toUpperCase</span><span class='o'>()</span> <span class='o'>+</span> <span class='s'>&quot;\n&quot;</span><span class='o'>);</span>
      <span class='o'>});</span>
    <span class='o'>});</span>
  <span class='o'>});</span>
<span class='o'>}</span>
<span class='k'>catch</span><span class='o'>(</span><span class='n'>IOException</span> <span class='n'>e</span><span class='o'>)</span> <span class='o'>{</span>
  <span class='c1'>// handle as appropriate. Can still have suppressed exceptions on it.</span>
<span class='o'>}</span>
</code></pre>
</div>
<p>This is just one way this could be implemented; because it only relies on functions, how expressive the APIs are is up to the library designer, <em>not</em> the language designer. An important distinction. Why build special scenarios into the compiler when one language feature can provide the flexibility you need?</p>

<p>Now - is this as short and tab-friendly as the Java 7 feature? Admittedly no. However, the goal of the try-with-resources is not to save on typing, but rather, to ensure resource management is as accurate as possible, relying as little as possible on the developer to dial-in boilerplate, and error-prone exception management.</p>

<p>Here is a short run-down of the library changes that would be required to support this particular code:</p>

<ul>
<li><code>java.io.File</code> needs a new method called <code>read</code> which takes a String file name, and also takes a function that accepts a <code>java.io.FileReader</code>, and returns nothing. The code block may throw an <code>IOException</code>. This method does all of the resource management for the <code>FileReader</code> it provides to the function. If the code block throws an exception and closing the file reader also throws an exception, the method would add the close exception to the main exception as a suppressedException (just like the language feature would). <code>java.io.File</code> also needs a new method called <code>write</code> which takes a String file name, and also takes a function that accepts a <code>java.io.FileWriter</code>, and again, returns nothing. This can also throw and <code>IOException</code>, and just like the read method, it handles all of the minutia of exception suppression and resource-closing. <code>java.io.FileReader</code> needs a new method called <code>eachLine</code> that simple scans for line-terminators and lets a provided function see the string representation of each line. The function may throw <code>IOException</code>, and the method simply lets IOException propagate.</li>
</ul>

<p>Just to circle back around - Java today could support the &#8220;eachLine&#8221; method on FileReader via enhanced-for loop, if the &#8220;eachLine&#8221; method returned an <code>Iterable&lt;String&gt;</code> (as opposed to accepting a block of code) - it could look something like this:</p>
<div class='highlight'><pre><code class='java'><span class='k'>for</span><span class='o'>(</span><span class='n'>String</span> <span class='n'>line</span> <span class='o'>:</span> <span class='n'>in</span><span class='o'>.</span><span class='na'>eachLine</span><span class='o'>())</span> <span class='o'>{</span>
  <span class='n'>out</span><span class='o'>.</span><span class='na'>write</span><span class='o'>(</span><span class='n'>line</span><span class='o'>.</span><span class='na'>toUpperCase</span><span class='o'>()</span> <span class='o'>+</span> <span class='s'>&quot;\n&quot;</span><span class='o'>);</span>
<span class='o'>}</span>
</code></pre>
</div>
<p>Sadly, this feature will be here with Java 7, and lambdas will not. As such, it&#8217;s yet another way to buy time without lambdas, and look a little better next to the C# features list.</p>
  ]]></description>
</item>

	<item>
  <title>Distilling Mirah: Type Inference</title>
  <link>http://realjenius.com/2010/10/05/distilling-mirah-1/</link>
  <author>R.J. Lorimer</author>
  <pubDate>2010-10-05T00:00:00-07:00</pubDate>
  <guid>http://realjenius.com/2010/10/05/distilling-mirah-1/</guid>
  <description><![CDATA[
     <p>Recently, I&#8217;ve been watching the work of a handful of developers on a new programming language: <a href='http://www.mirah.org'>Mirah</a>. As a fan of the <a href='http://www.ruby-lang.org'>Ruby programming language</a> and a slave to the Java overlords, Mirah offers instant appeal to me, as it borrows the core Ruby syntax almost verbatim, but creates true Java class files runnable on any Java VM. This decision makes perfect sense, considering the originator of Mirah is <a href='http://blog.headius.com'>Charlie Nutter</a>, one of the key developers of JRuby, a language heavily invested in both Ruby and Java. (Mirah actually reuses the JRuby parser at the time of this writing, if that gives you any indicator how similar the syntax is).</p>

<p>Because of my interest in the development of Mirah, I&#8217;ve decided to begin spelunking into the implementation as it stands today, sharing with you what is going on internally. Many of you are probably familiar with my &#8221;<a href='http://realjenius.com/category/distilling-jruby/'>Distilling JRuby</a>&#8221; series, and while these articles will likely read similarly, I suspect they will be more brief and hand-wavy. This is partially out of a desire to cover more topics over a short period of time, but also because the implementation for Mirah is very fluid, and is likely to change, rendering these articles invalid or at least out-dated.</p>

<p>Without further ado - let&#8217;s kick this pig. On to Mirah&#8217;s type-inferencing!</p>
<div class='seriesNote'>
<p>This is <strong>Part 1</strong> in a series on <a href='http://www.mirah.org'>Mirah</a> I have started, called "Distilling Mirah" - the <a href='http://realjenius.com/category/distilling-mirah/'>entire series is available here</a>.</p>
<p><em>As with all my JRuby articles, I will be showing a number of partial snippets - these are meant to imply the idea without covering all of the code that may be rather spooky when considering all of the corner cases. I've tried to reduce the code to its bare important essentials. Oh, and as with the JRuby articles, I reserve the right to temporarily lie for simplicity's sake.</em></p>
</div>
<h2 id='mirah_overview'>Mirah Overview</h2>

<p>There are a few key concepts that need to be discussed regarding Mirah before we get started:</p>

<ul>
<li>Mirah is not Ruby! Mirah looks like Ruby at first glance, but that is only superficial in nature. We will see why over the next series of topics.</li>

<li>Unlike JRuby, Mirah is not implemented in Java (well, mostly not). It is actually implemented in Ruby - this is going to make the way we traverse the code in these articles very different than the JRuby series.</li>

<li>While I say that Mirah borrows the Ruby syntax, it has to modify and add certain structures to fit the mold which has been carved for it. So while it is possible to write some programs that are almost true Ruby syntax, most Mirah programs will have a few extra sprinkles.</li>

<li>Mirah is statically typed, and compiles to standard Java bytecode. This is one of the key reasons that Mirah is not 100% Ruby-grammar compatible.</li>

<li>Mirah is designed from the ground up to be a language specification that can be implemented on several platforms (.NET is a perfect example). This introduces indirection in the code that may, at first, seem confusing.</li>

<li>One of the key principals of Mirah is to avoid runtime encumbrances if at all possible. What this means is that all features in Mirah as it currently stands are implemented by either a compiler plug-in, or by using existing core libraries of the underlying platform (or a combination, of course). This goal is to hopefully avoid the 3-5 MB ball-and-chain that many languages (i.e. Scala, Clojure, JRuby) hang around your neck to run deployed code. The idea being that, if you want runtime features, you can bring Mirah modules in per your own decision, but if you want to fit a Mirah program on a micro-controller that can run Java bytecode (or Dalvik <em>cough</em>), you should be able to by forgoing some of those features that require large runtime libraries.</li>
</ul>

<p>The Mirah site can be found at <a href='http://www.mirah.org'>http://www.mirah.org</a>, and the official Mirah &#8216;master&#8217; repo is available at github: <a href='http://github.com/mirah/mirah'>http://github.com/mirah/mirah</a>. Feel free to checkout and follow along, although one last disclaimer - the code is changing <em>quickly</em>, so my articles are bound to fall out of the times.</p>

<p>I&#8217;d suggest before proceeding you familiarize yourself with the language syntax - I don&#8217;t plan to stop along the way.</p>

<h2 id='a_background_on_type_inference'>A Background on Type Inference</h2>

<p>Most JVM language replacements that are garnering attention right now in one way or another avoid explicit typing in the syntax to some degree. Languages that are compiled to normal byte-code with some degree of implicit typing, must involve some form of type inference. This is the process of statically analyzing code to determine the runtime types the code is using by <em>inferring</em> from the use of variables and parameters. Statically compiled languages on the VM must do this, because Java bytecode (and the VM) expects to work with types - and if the compiler can&#8217;t figure it out, it can&#8217;t compile the bytecode.</p>

<p>Consider this Java statement:</p>
<div class='highlight'><pre><code class='java'><span class='n'>HashMap</span><span class='o'>&lt;</span><span class='n'>String</span><span class='o'>,</span><span class='n'>String</span><span class='o'>&gt;</span> <span class='n'>myMap</span> <span class='o'>=</span> <span class='k'>new</span> <span class='n'>HashMap</span><span class='o'>&lt;</span><span class='n'>String</span><span class='o'>,</span><span class='n'>String</span><span class='o'>&gt;();</span>
</code></pre>
</div>
<p>There is really no reason you need to define the left-hand side (the declaration) so explicitly, considering that the right-hand side (the assignment) has already told you exactly what the variable is. Surely this should be sufficient:</p>
<div class='highlight'><pre><code class='java'><span class='n'>var</span> <span class='n'>myMap</span> <span class='o'>=</span> <span class='k'>new</span> <span class='n'>HashMap</span><span class='o'>&lt;</span><span class='n'>String</span><span class='o'>,</span><span class='n'>String</span><span class='o'>&gt;();</span>
</code></pre>
</div>
<p>Anyone familiar with C# will likely recognize this syntax convenience. Of course, this is simple example, because you only have to examine this one line to infer the variable type. Things get much more complex when there are control structures, methods, and other language features in the way.</p>

<p>That being said, type inferencing is a well-tread path - it&#8217;s certainly not unique to JVM languages; far from it. There are different levels of type inference, with the most complete often using something <a href='http://en.wikipedia.org/wiki/Type_inference'>like Hindley-Milner</a> to deduce types recursively (excellent description <a href='http://www.codecommit.com/blog/scala/what-is-hindley-milner-and-why-is-it-cool'>of Hindley-Milner by Daniel Spiewak on his blog</a>).</p>

<h2 id='mirahs_type_inferencing'>Mirah&#8217;s Type Inferencing</h2>

<p>As it stands today, Mirah currently implements a variant of type inference somewhere between true &#8220;local&#8221; type inference, and fully recursive type inference like Hindley-Milner. Mirah&#8217;s inference uses a multi-pass infer process, where the first phase does simple local inference (or line-by-line inference), and then subsequent passes are made, looking for new type resolutions from those higher constructs. For example, consider these two Mirah methods:</p>
<div class='highlight'><pre><code class='ruby'><span class='k'>def</span> <span class='nf'>method_a</span><span class='p'>()</span>
  <span class='k'>return</span> <span class='n'>method_b</span><span class='p'>(</span><span class='mi'>5</span><span class='p'>)</span> <span class='o'>+</span> <span class='n'>method_b</span><span class='p'>(</span><span class='mi'>6</span><span class='p'>)</span>
<span class='k'>end</span>

<span class='k'>def</span> <span class='nf'>method_b</span><span class='p'>(</span><span class='n'>x</span><span class='ss'>:int</span><span class='p'>)</span>
  <span class='k'>return</span> <span class='n'>x</span> <span class='o'>*</span> <span class='o'>-</span><span class='mi'>1</span>
<span class='k'>end</span>
</code></pre>
</div>
<p>In this case, &#8216;method_a&#8217; is obviously dependent upon &#8216;method_b&#8217; - but if &#8216;method_a&#8217; is inferred first, it will have no way to know what it&#8217;s return type is, because method_b hasn&#8217;t been inferred yet. In this case, &#8216;method_a&#8217; is &#8216;deferred&#8217; for a later inference pass. Shortly thereafter, &#8216;method_b&#8217; will be processed, and since it can be completely analyzed through local inference, it will resolve to return an int. At that point, method_a can look at the two invocations that are involved in the return statement, and can in turn determine that it should also return an int.</p>

<h2 id='the_algorithm'>The Algorithm</h2>

<p>From an implementation standpoint, Mirah does this inference by utilizing the ASTs generated from the source. Each AST knows individually how to infer itself based on its recursive contents - this is something we&#8217;ll investigate in more detail shortly.</p>

<p>Mirah defines a namespace and class called Typer that is used to orchestrate this entire process. The Typer is asked to analyze each AST tree parsed by Mirah individually, and then to iteratively resolve:</p>
<div class='highlight'><pre><code class='ruby'><span class='n'>typer</span> <span class='o'>=</span> <span class='no'>Typer</span><span class='o'>.</span><span class='n'>new</span>
<span class='n'>asts</span><span class='o'>.</span><span class='n'>each</span> <span class='p'>{</span> <span class='o'>|</span><span class='n'>ast</span><span class='o'>|</span> <span class='n'>typer</span><span class='o'>.</span><span class='n'>infer</span><span class='p'>(</span><span class='n'>ast</span><span class='p'>)</span> <span class='p'>}</span>
<span class='n'>typer</span><span class='o'>.</span><span class='n'>resolve</span>
</code></pre>
</div>
<p>The infer method for an individual AST node is pretty straightforward:</p>
<div class='highlight'><pre><code class='ruby'><span class='k'>class</span> <span class='nc'>Typer</span>
  <span class='k'>def</span> <span class='nf'>infer</span><span class='p'>(</span><span class='n'>node</span><span class='p'>)</span>
    <span class='n'>node</span><span class='o'>.</span><span class='n'>infer</span><span class='p'>(</span><span class='nb'>self</span><span class='p'>)</span>
    <span class='c1'># error handling business</span>
  <span class='k'>end</span>
<span class='k'>end</span>
</code></pre>
</div>
<p>Notice that the typer passes itself into the node - this allows the nodes to callback into the typer for a variety of reasons. For example, each node has to decide for itself whether or not it has enough information to infer. If it doesn&#8217;t, it will tell the typer that it needs to be &#8216;deferred&#8217;, meaning it doesn&#8217;t yet have enough information. All this effectively does is record the node for later:</p>
<div class='highlight'><pre><code class='ruby'><span class='k'>class</span> <span class='nc'>Typer</span>
  <span class='k'>def</span> <span class='nf'>defer</span><span class='p'>(</span><span class='n'>node</span><span class='p'>)</span>
    <span class='vi'>@deferred_nodes</span> <span class='o'>&lt;&lt;</span> <span class='n'>node</span>
  <span class='k'>end</span>
<span class='k'>end</span>
</code></pre>
</div>
<p>So the typer calls infer on the top level AST node, at which point the AST hierarchy will recurse, inferring and deferring nodes as appropriate. After the first recursive inference pass, the typer is then asked to resolve AST nodes iteratively until all nodes are inferred, or until no progress is made:</p>
<div class='highlight'><pre><code class='ruby'><span class='k'>class</span> <span class='nc'>Typer</span>
  <span class='k'>def</span> <span class='nf'>resolve</span>
    <span class='n'>old_len</span> <span class='o'>=</span> <span class='vi'>@deferred_nodes</span><span class='o'>.</span><span class='n'>length</span>
    <span class='k'>while</span> <span class='kp'>true</span>
      <span class='vi'>@deferred_nodes</span><span class='o'>.</span><span class='n'>each</span> <span class='k'>do</span> <span class='o'>|</span><span class='n'>node</span><span class='o'>|</span>
        <span class='n'>type</span> <span class='o'>=</span> <span class='n'>infer</span><span class='p'>(</span><span class='n'>node</span><span class='p'>)</span>
        <span class='k'>if</span> <span class='n'>type</span> <span class='o'>!=</span> <span class='kp'>nil</span>
          <span class='vi'>@deferred_nodes</span><span class='o'>.</span><span class='n'>remove</span><span class='p'>(</span><span class='n'>node</span><span class='p'>)</span>
        <span class='k'>end</span>
      <span class='k'>end</span>
    
      <span class='k'>if</span> <span class='vi'>@deferred_nodes</span><span class='o'>.</span><span class='n'>length</span> <span class='o'>==</span> <span class='mi'>0</span>
        <span class='k'>break</span>
      <span class='k'>elsif</span> <span class='n'>old_len</span> <span class='o'>==</span> <span class='vi'>@deferred_nodes</span><span class='o'>.</span><span class='n'>length</span>
        <span class='k'>raise</span> <span class='c1'># can&#39;t infer error!</span>
      <span class='k'>end</span>
    <span class='k'>end</span>
  <span class='k'>end</span>
<span class='k'>end</span>
</code></pre>
</div>
<h2 id='ast_working_together'>AST Working Together</h2>

<p>Understanding the concept of the AST recursively inferring is the key component to understanding the typer. Consider, for example, the statement <code>x = method_b(5)</code> - this is represented by a tree of AST nodes. For those of you with experience in parsers, or experience with my previous JRuby articles, it probably won&#8217;t be too hard to derive the types of nodes involved - it&#8217;s basically this:</p>
<div class='highlight'><pre><code class='text'>LocalDeclaration
|
.-- LocalAssignment (type_node)
    |
    .-- FunctionalCall (value)
        |
        .-- Fixnum (parameters)
            |
            .-- &quot;5&quot; (literal)
</code></pre>
</div>
<p>The idea is that the declaration will ask the assignment, which will in turn ask the call being made with the parameter types in play, and will then return the type of the call return type. Here is a sketch of the various infer methods for these nodes:</p>
<div class='highlight'><pre><code class='ruby'><span class='k'>class</span> <span class='nc'>LocalDeclaration</span>
  <span class='k'>def</span> <span class='nf'>infer</span><span class='p'>(</span><span class='n'>typer</span><span class='p'>)</span>
    <span class='n'>type</span> <span class='o'>=</span> <span class='vi'>@type_node</span><span class='o'>.</span><span class='n'>infer</span><span class='p'>(</span><span class='n'>typer</span><span class='p'>)</span>  <span class='c1'>#type_node is the local assignment</span>
    <span class='k'>if</span><span class='p'>(</span><span class='o'>!</span><span class='n'>type</span><span class='p'>)</span>
      <span class='n'>typer</span><span class='o'>.</span><span class='n'>defer</span><span class='p'>(</span><span class='nb'>self</span><span class='p'>)</span>
    <span class='k'>end</span>
    <span class='k'>return</span> <span class='n'>type</span>
  <span class='k'>end</span>
<span class='k'>end</span>

<span class='k'>class</span> <span class='nc'>LocalAssignment</span>
  <span class='k'>def</span> <span class='nf'>infer</span><span class='p'>(</span><span class='n'>typer</span><span class='p'>)</span>
    <span class='n'>type</span> <span class='o'>=</span> <span class='vi'>@value</span><span class='o'>.</span><span class='n'>infer</span><span class='p'>(</span><span class='n'>typer</span><span class='p'>)</span> <span class='c1'>#value is the &quot;functional&quot; call.</span>
    <span class='k'>if</span><span class='p'>(</span><span class='o'>!</span><span class='n'>type</span><span class='p'>)</span>
      <span class='n'>typer</span><span class='o'>.</span><span class='n'>defer</span><span class='p'>(</span><span class='nb'>self</span><span class='p'>)</span>
    <span class='k'>end</span>
    <span class='k'>return</span> <span class='n'>type</span>
  <span class='k'>end</span>
<span class='k'>end</span>

<span class='k'>class</span> <span class='nc'>FunctionalCall</span>
  <span class='k'>def</span> <span class='nf'>infer</span><span class='p'>(</span><span class='n'>typer</span><span class='p'>)</span>
    <span class='vi'>@parameters</span><span class='o'>.</span><span class='n'>each</span> <span class='p'>{</span> <span class='o'>|</span><span class='n'>param</span><span class='o'>|</span> <span class='n'>param</span><span class='o'>.</span><span class='n'>infer</span><span class='p'>(</span><span class='n'>typer</span><span class='p'>)</span> <span class='p'>}</span>
    <span class='k'>if</span> <span class='c1'>#all parameters inferred, and method with params and scope is known</span>
      <span class='k'>return</span> <span class='n'>typer</span><span class='o'>.</span><span class='n'>method_type</span><span class='p'>(</span><span class='vi'>@method_name</span><span class='p'>,</span> <span class='n'>method_scope</span><span class='p'>,</span> <span class='vi'>@parameters</span><span class='p'>)</span>
    <span class='k'>else</span>
       <span class='n'>typer</span><span class='o'>.</span><span class='n'>defer</span><span class='p'>(</span><span class='nb'>self</span><span class='p'>)</span>
       <span class='k'>return</span> <span class='kp'>nil</span>
    <span class='k'>end</span>
  <span class='k'>end</span>
<span class='k'>end</span>

<span class='k'>class</span> <span class='nc'>FixNum</span>
  <span class='k'>def</span> <span class='nf'>infer</span><span class='p'>(</span><span class='n'>typer</span><span class='p'>)</span>
    <span class='k'>return</span> <span class='n'>typer</span><span class='o'>.</span><span class='n'>fixnum_type</span><span class='p'>(</span><span class='vi'>@literal</span><span class='p'>)</span> <span class='c1'>#literal is &#39;5&#39;</span>
  <span class='k'>end</span>
<span class='k'>end</span>
</code></pre>
</div>
<p>A few things to note here:</p>

<ul>
<li>This is totally pseudo code - the actual code has all kinds of branches for caching and other good bits.&lt;/li&gt;</li>

<li>The one literal we have, Fixnum, calls back into the typer to get the actual fixnum type - we&#8217;ll see this come in to play momentarily.</li>

<li>The typer has the ability to look up a method type by a signature - when methods are scanned during type inference, they record themselves in the typer for other nodes, like this one, to use when inferring since they are one case of node &#8220;hopping&#8221;, where one AST can be linked to another by reference.</li>

<li>We&#8217;re dodging how the functional call determines things like &#8216;method scope&#8217; for now.</li>
</ul>

<h2 id='resolving_literals'>Resolving Literals</h2>

<p>As noted above, the Fixnum node is asking the typer to give it back a fixnum type. This is done for all of the literal types. It&#8217;s done this way so that the platform implementation (in this particular case, Java) can plug in a particular type. So in this particular case, the Java implementation, in the JVM::Types module, provides a FixnumLiteral that looks at the provided value, and determines where in the hierarchy it belongs (for you Java folks, that&#8217;s byte, short, int, long, etc). When asked to actually compile, these AST nodes actually know how to generate the ultra-fast JVM bytecode-ops for primitives.</p>

<h2 id='type_annotations'>Type Annotations</h2>

<p>As seen in one of the snippets above, Mirah supports type definitions for places where typing is either required (due to a lack of inference) or desired (widening a type, for example). Forgoing the fact this is a contrived implementation for a moment, consider this method:</p>
<div class='highlight'><pre><code class='ruby'><span class='n'>import</span> <span class='n'>java</span><span class='o'>.</span><span class='n'>util</span><span class='o'>.</span><span class='n'>Map</span>
<span class='n'>import</span> <span class='n'>java</span><span class='o'>.</span><span class='n'>util</span><span class='o'>.</span><span class='n'>HashMap</span>
<span class='k'>class</span> <span class='nc'>SomeClass</span> 
  <span class='k'>def</span> <span class='nf'>singleton_map</span><span class='p'>(</span><span class='n'>a</span><span class='ss'>:string</span><span class='p'>,</span> <span class='n'>b</span><span class='ss'>:string</span><span class='p'>)</span><span class='ss'>:Map</span>
    <span class='n'>map</span> <span class='o'>=</span> <span class='no'>HashMap</span><span class='o'>.</span><span class='n'>new</span>
    <span class='n'>map</span><span class='o'>.</span><span class='n'>put</span><span class='p'>(</span><span class='n'>a</span><span class='p'>,</span><span class='n'>b</span><span class='p'>)</span>
    <span class='k'>return</span> <span class='n'>map</span>  
  <span class='k'>end</span>
<span class='k'>end</span>
</code></pre>
</div>
<p>Here we are declaring both variable types so we can control inputs, and then we are declaring the return type. The reason you might want to declare a return type like this is so that the compiled method doesn&#8217;t expose too narrow of an implementation. Remember, we&#8217;re compiling to Java class files here - so if the compiled type inferred that the method returned a HashMap, that is a contraint we may never be able to change in the future. By changing it to &#8216;Map&#8217;, we can adjust the API like we would in the Java world to avoid tying ourselves to an implementation. To see this in action, here&#8217;s the output from mirahc when asked to generate Java code for this with and without the return type:</p>
<div class='highlight'><pre><code class='java'><span class='c1'>// With:</span>
<span class='kd'>public</span> <span class='kd'>class</span> <span class='nc'>SomeClass</span> <span class='kd'>extends</span> <span class='n'>java</span><span class='o'>.</span><span class='na'>lang</span><span class='o'>.</span><span class='na'>Object</span> <span class='o'>{</span>
  <span class='kd'>public</span> <span class='n'>java</span><span class='o'>.</span><span class='na'>util</span><span class='o'>.</span><span class='na'>Map</span> <span class='nf'>singleton_map</span><span class='o'>(</span><span class='n'>java</span><span class='o'>.</span><span class='na'>lang</span><span class='o'>.</span><span class='na'>String</span> <span class='n'>a</span><span class='o'>,</span> <span class='n'>java</span><span class='o'>.</span><span class='na'>lang</span><span class='o'>.</span><span class='na'>String</span> <span class='n'>b</span><span class='o'>)</span> <span class='o'>{</span>
    <span class='n'>java</span><span class='o'>.</span><span class='na'>util</span><span class='o'>.</span><span class='na'>HashMap</span> <span class='n'>map</span> <span class='o'>=</span> <span class='k'>new</span> <span class='n'>java</span><span class='o'>.</span><span class='na'>util</span><span class='o'>.</span><span class='na'>HashMap</span><span class='o'>();</span>
    <span class='n'>map</span><span class='o'>.</span><span class='na'>put</span><span class='o'>(</span><span class='n'>a</span><span class='o'>,</span> <span class='n'>b</span><span class='o'>);</span>
    <span class='k'>return</span> <span class='n'>map</span><span class='o'>;</span>
  <span class='o'>}</span>
<span class='o'>}</span>

<span class='c1'>// Without:</span>
<span class='kd'>public</span> <span class='kd'>class</span> <span class='nc'>SomeClass</span> <span class='kd'>extends</span> <span class='n'>java</span><span class='o'>.</span><span class='na'>lang</span><span class='o'>.</span><span class='na'>Object</span> <span class='o'>{</span>
  <span class='kd'>public</span> <span class='n'>java</span><span class='o'>.</span><span class='na'>util</span><span class='o'>.</span><span class='na'>HashMap</span> <span class='nf'>singleton_map</span><span class='o'>(</span><span class='n'>java</span><span class='o'>.</span><span class='na'>lang</span><span class='o'>.</span><span class='na'>String</span> <span class='n'>a</span><span class='o'>,</span> <span class='n'>java</span><span class='o'>.</span><span class='na'>lang</span><span class='o'>.</span><span class='na'>String</span> <span class='n'>b</span><span class='o'>)</span> <span class='o'>{</span>
    <span class='n'>java</span><span class='o'>.</span><span class='na'>util</span><span class='o'>.</span><span class='na'>HashMap</span> <span class='n'>map</span> <span class='o'>=</span> <span class='k'>new</span> <span class='n'>java</span><span class='o'>.</span><span class='na'>util</span><span class='o'>.</span><span class='na'>HashMap</span><span class='o'>();</span>
    <span class='n'>map</span><span class='o'>.</span><span class='na'>put</span><span class='o'>(</span><span class='n'>a</span><span class='o'>,</span> <span class='n'>b</span><span class='o'>);</span>
    <span class='k'>return</span> <span class='n'>map</span><span class='o'>;</span>
  <span class='o'>}</span>
<span class='o'>}</span>
</code></pre>
</div>
<p>Individual AST nodes know about these definitions (sometimes known as forced types), and will respect those over the corresponding inferred types. That&#8217;s not to say that it will just take them for granted; the type inference still occurs. In the example above, the method body is still inferred to ensure it returns a type that can be widened to &#8216;java.util.Map&#8217; - otherwise the code will cause runtime errors in the VM. Here&#8217;s a snippet of the method definition AST analysis:</p>
<div class='highlight'><pre><code class='ruby'><span class='k'>class</span> <span class='nc'>MethodDefinition</span>
  <span class='k'>def</span> <span class='nf'>infer</span><span class='p'>(</span><span class='n'>typer</span><span class='p'>)</span>
    <span class='n'>forced_type</span> <span class='o'>=</span> <span class='vi'>@return_type</span>
    <span class='n'>inferred_type</span> <span class='o'>=</span> <span class='vi'>@body</span><span class='o'>.</span><span class='n'>infer</span><span class='p'>(</span><span class='n'>typer</span><span class='p'>)</span>
    <span class='n'>actual_type</span> <span class='o'>=</span> <span class='k'>if</span> <span class='n'>forced_type</span><span class='o'>.</span><span class='n'>nil?</span>
      <span class='n'>inferred_type</span>
    <span class='k'>else</span>
      <span class='n'>forced_type</span>
    <span class='k'>end</span>

    <span class='k'>if</span> <span class='o'>!</span><span class='n'>actual_type</span><span class='o'>.</span><span class='n'>is_parent</span><span class='p'>(</span><span class='n'>inferred_type</span><span class='p'>)</span>
      <span class='k'>raise</span> <span class='s2'>&quot;inference error&quot;</span>
    <span class='k'>end</span>
    <span class='k'>return</span> <span class='n'>actual_type</span>
  <span class='k'>end</span>
<span class='k'>end</span>
</code></pre>
</div>
<p>The return_type field will be set by the parser if provided, and takes precedent so long as it&#8217;s still able to be used in place of the actual inferred type of the method body.</p>

<h2 id='uncovered_topics'>Uncovered Topics</h2>

<p>So this was a quick spin through Mirah-land, but even for the inference engine, a lot was left on the table if you&#8217;d like to explore from here:</p>

<ul>
<li>Finding &#8220;native&#8221; types (in this case, calls into and returning Java types)</li>

<li>Tracking class/method scope when inferring</li>

<li>Inferring against intrinsics (such as &#8217;+&#8217;, and &#8216;||&#8217;)</li>

<li>Dealing with multi-node inference - several nodes, like &#8216;MethodDefinition&#8217; are expected to infer several parts, including arguments, return type, throws types, etc. This increases the complexity of the implementation, but doesn&#8217;t have much impact on concept.</li>

<li>Superclasses, invocation of &#8216;super&#8217;, overriding, overloading, etc.</li>

<li>Framework vs. Implementation (i.e. JVM) Responsibilities</li>
</ul>

<p>Stay tuned as the Mirah story unfolds!</p>
  ]]></description>
</item>

</channel>
</rss>