Saturday, August 21, 2010

Lazy Coder Cuisine, simple snacks, drinks: (fake) Key Lime Pancakes, Chunky Monkey (drink)

It has been a while since I have written about food or drinks. That does not mean I hadn't been experimenting with simple to make delicious food and drinks. Rather it is just an indication that one driving force in these experiments has been one of 3 cornerstones of good programmer productivity, laziness. And while that approach can lead to good discoveries, it does not lead to writing of those discoveries.

But since I just made another nice discovery, and since I am in semi-active blog-writing mood (due to having forced myself to write previous tech-heavy article last night!), let's review 2 simple pieces of good stuff: simple "fake" dessert (or just sweet complement to breakfast), and a simple alcoholic drink. And I am hoping this act of documentation might lead to my remembering more of document-worthy results I have had... if not, I will just need to write some more about blackberry beer or something. But I digress.

1. Key Lime Pancakes

Ok. First a disclaimer: this is not really Key Lime anything -- no limes are involved, nor anything from the Key west. Name is just inspired due to similarity of taste to Key Lime Pie. So consider this a "fake" recipe, something simple to make that imitates a better known dish. :-)

Making Key Lime Pancakes is rather simple -- very lazy-friendly -- and goes like this:

  1. Make basic pancakes (laziest way: use Walmart's pancake mix, only add water; more refined is to google for buttermilk pancake recipe, use that), make sure to fry them in butter (my preference is salted butter, I assume unsalted is ok for lower sodium intake)
  2. Spread thin (or, if you prefer, thick) layer of Lemon Curd (ready-made one works fine; I used Trader Joe's affordable yet good variant) on pancakes
  3. Add whipped cream -- use canned version for additional lazy points (as usual, Trader Joe's has good price/quality ratio), that is, spray some whipped cream on top of lemon curd
  4. Enjoy!

And there you have it! Actually I wish I had taken a snapshot of the result, but either way that would not convey the taste. Sweet taste of food coupled with irresistable satisfaction from making it happen with very low effort AND with limited budget. Good stuff, will be one of desserts included in Tatu's Fenno-American Cookbook, should one get written one day.

Since this is rather sweet stuff (albeit with nice acidic overtones), it's best to cleanse one's palate with something... which leads us to the second recipe.

2. Chunky Monkey, the Drink (aka Banana Jack)

One experiment I did over a year ago was to figure out if I could think of a new whiskey based drink. Specifically, a bourbon-based one -- there is no need to commit cardinal sin of spoiling malt whiskys with alien substances.

Of different combinations, only one deserves mention, with recipe like:

  1. Pour some Bourbon (like Jack Daniel's), say 5cl
  2. Add some banana liqueur; ratio to use depends on how strong banana taste one likes; 2-to-1 seems like a reasonable ratio, so 2.5 cl

This drink can be served cold (if so, pour on ice cubes; not shaved ice), but I actually prefer it warm: whisk(e)ys are sensitive to cold in my opinion.
The reason this is a nice drink is that sweetness nicely mellows whiskey taste, similar to how Manhattan cocktail works. And when choosing component ratios properly, drink should not be overly sweet or artificial (one risk with banana liquers)

I hope name I chose has not already been taken. I guess I could alternatively also call it "Banana Jack".

3. Send me patches!

One of best things that ever happened to me and my open source projects was that others started using things I wrote. And sent bug reports, improvements ideas and comments.

In same spirit, if you think of improvement ideas, please do send patches! :-D

Friday, August 20, 2010

Every day Jackson usage, part 1: Immutable objects

Here's something that has been requested by multiple readers: an article detailing how to use Jackson to support specific usage patterns. "Jackson usage patterns" if you will.
And first topic I want to cover is.... Immutable Objects.

1. Immutable Objects: what, why?

Immutable objects in Java are objects that are either stateless (behaviour-only) or where state is set at construction and can not be changed.
For example, here is a simple immutable object class:

 public class Point {
  private final int x, y;

  public Point(int x, int y) {
   this.x = x;
   this.y = y;
  public int getX() { return x; }
  public int getY() { return y;

The main difference to more common approach is that there are no setters; instead, values of x and y are assigned just once in constructor. That is actually a big difference, and makes this a better approach for many use cases.

But why is it better? One side benefit is just simplicity; fewer methods to write (and maintain), less code, is generally better. But the main benefit is that immutable objects are thread-safe requiring no synchronization: instances can be freely shared and reused between different threads. Immutable objects are also usable as Map keys (in fact Map keys are required to be immutable; or at least never modified while used as a key). This allows very efficient reuse using fly-weight pattern and canonical objects. In fact, unless mutability is specifically needed I try to keep objects immutable, as sort of baseline.

There are also challenges: inability to change state complicates many things. But it is worth noting that immutability only affects instance; and system-level changing of things is quite easy. A common pattern is that of defining factory methods like:

 public class Point {
  // ...
  public Point move(int byX, int byY) { 
    return new Point(x+byX, y+byY);

so that instances are never modified; instead, new instances are constructed based on previous state and delta of some sort. This works nicely for many cases, and is also basis for many lock-free data structures.

But enough about object immutability itself. What is more interesting is if and how one can support such use cases with Jackson.

2. Can Jackson do it?

Initially it might seem unlikely that Jackson can work with immutable objects: after all, aren't Beans required to have getters and setters? "Classic" Java Beans do indeed need setters (mutators). And as a consequence many data binding frameworks (JAXB) require setters, or access to public fields.

But Jackson is neither limited to Beans -- it can work with many other kinds of POJOs -- nor does it require setters for injecting data in. And unlike many serialization frameworks, Jackson does not require access to object fields either (although it can certainly use them when instructed).

As with most Jackson functionality, there are multiple ways to achieve immutability. Let's have a look at them one by one.

3. Simple Immutable Objects using Creator methods

The simplest way to make Jackson produce immutable objects is to instruct it to do what Point class was already doing: make Jackson use constructor to feed in data. This is similar to how Dependency Injection frameworks (like Guice do), and requires use of simple annotations (mix-in annotations work fine):

 public class Point {
  private final int x, y;

  public Point(@JsonProperty("x") int x, @JsonProperty("y") int y) {
   this.x = x;
   this.y = y;

and with this, Jackson will use constructor for passing logical properties "x" and "y", instead of trying to use fields or set methods. The only difference to "regular" properties is that @JsonProperty is not optional for constructor arguments, because bytecode does not store names of parameters and they must be explicitly specified. As with other properties one can configure different aspects, including custom deserializer to use if any, specific subtype to use and so on.

Alternatively one can also define factory methods (constructors and factory methods are collectively referred to as "Creator methods" in Jackson documentation), like so:

  public class Point {
   public static Point makeAPoint(@JsonProperty("x") int x, @JsonProperty("y") int y) {
    return new Point(x, y);

Simple? Note too that you can use Creator methods with other kinds of POJOs. You can also mix and match field access and setter access; if so, Creators are always called first to instantiate an Object, and setters and fields are used afterwards. So you don't have to go all immutable; it is often beneficial to just make certain fields immutable.

4. Faking Immutability

One thing that I did not yet mention is that there is difference between complete immutability (as shown above), and just perceived immutability. By latter I mean that there is no way to change state of the object form outside (except via Reflection, more on this in a minute) -- if you can not change the state, it is as good as immutable. Consider example where fields "x" and "y" were not marked as final: fields are still private, and therefore inaccessible from outside. But they can still be modified via reflection. Since we are not considering security implications here, such bean would be about as good (with respect to benefits of immutability) as one were fields were forced final.

With Jackson you could actually use such fields as well; by having Point class like this:

 public class Point {
  @JsonProperty private int x;
  private int y;

  public Point() { }

  @JsonProperty private void setY(int y) { this.y = y; }

  public int getX() { return x; }
  public int getY() { return y; }

So during deserialization, Jackson would directly access field "x" (using Reflection) and call method "setY" to set value of "y". But since regular code can not modify things further, object would work just as truly immutable one does. This can lead to even simpler code if you just annotate private fields so there is no need to copy values in constructor.

5. Immutabilty by interface / implementation separation

Yet another possibility to achieve perceived immutability is to separate interface of an object into multiple pieces: public read-only (immutable) part that is exposed to application, and mutable part that is used for actual data binding. In our case we could have basic Point interface, implemented by PointImpl class; latter with necessary fields and possibly setters; and interface just having accessors (getters). So as long as application code only deals with interfaces we achieve immutability from design perspective.

But the problem here is that of dependencies; consider a POJO like:

 public class Circle {
  public Point center;
  public int radius;

how would Jackson know that 'center' instance really needs to be of type PointImpl, as Point is just an interface (and can not be created)? Simplest way is to use annotation @JsonDeserialize, which can define actual (sub)type to use (as well as custom deserializer to use; or for Collection and Map types, actual types of values and map keys, and custom deserializers for them too!):

 public class Circle {
  public Point center;

public int radius; }

and things would work as expected (alternative would be custom deserializer which is bit more work) -- 'center' would always be an instance of PointImpl.

6. Even crazier stuff: Materialize it!

Ok: when I said that one can not just create an instance of an interface, I omitted something cool that Jackson 1.6 will bring: ability to "materialize interfaces". So even though 1.6 has not yet been released (it will be shortly, by end of August!), let's have a sneak peek at this cool feature.

Actually, there is really very little to say, except that instead of having to define PointImpl, one could just register bean materializer (see this piece of documentation for details):


and then Jackson would create an implementation class for any non-concrete Bean (abstract class or interface where all abstract methods are getters or setters) type and use it for deserialization. Pretty cool eh?

This is actually also another fakin' it method: materialized class actually has appropriate access (setters by default), but those are only visible to Jackson itself (or other code that uses Introspection to find methods).

7. More?

These are ways I can think of to make Jackson construct immutable objects. If you can think of others, let me know. :-)

But beyond this, I have some ideas of topics to write about, like

  • How to filter out stuff to serialize (JSON Views, @JsonIgnore)
  • Working with Polymorphic types (@JsonSerialize(as=...), @JsonTypeInfo, default typing, ...)
  • Working with Open Content (models)

And if/when you can think of other Jackson Usage Patterns, please let me know! I'm sure there are more than 3 areas of usage that could use some more documentation.

Saturday, August 14, 2010

Another interesting(-looking) data store on Java platform: Krati?

Ok, looks like there is one more storage option I really should investigate, Krati. What seems appealing (at first glance) is the understanding that performance optimization on Java platform are quite distinct from those for systems written in C/C++ (or on Erlang and other distinct platforms). And especially trying to make good use of big discrepancy between performance of random access versus sequential access; given that latter can be an order of magnitude faster, it may well make sense to add more processing to be able to sequential writes even if higher-level abstraction was concurrent random-access.

Of course there are lots and lots of other choices: from stripped-down "traditional" storage (like using MySQL InnoDB, see for example g414-inno) to BDB variants, Tokyo Cabinet and Redis. And higher-level systems that use roll-your-own storage (like Cassandra does by default). And this is good, I think; for truly optimal performance one-solution-cant-fit-all -- different storage options are best fits for different system designs.

Wednesday, August 11, 2010

Jackson and Inner Classes: yes, you can use, but they must be STATIC inner classes

Ok here is something I did not realize up until today: apparently proper usage of inner classes is an area of vast confusion within Java developer community. In fact there are a few web pages that suggest that Jackson could not be used with inner class values.

This is actually both true and false, due to pecularities of Java inner classes. Although inner classes were introduced as early as with Java 1.1 (to make working with AWT and then Swing easier, mostly), not everyone knows enough to use proper kind of inner class.

1. Long story short?

You can use static inner classes like this one:

  public class Outer {
    static class Inner {
      public int getX() { return 5;

for values without any problems. Just make sure that "static" is in there and you are golden.

So what is the problem? If you do not add static, resulting class is generally useless for Jackson as well as any other data binding framework (Hibernate, JAXB); can often be serialized, but never serialized into. To understand why, let's go back in time, to late 90s... to time when the first big batch of syntactic sugar was added in Java.

2. Anonymous, static, non-static inner classes?

Basically there are multiple kinds of inner classes: anonymous inner classes are ones used inline (for event handling for example); static ones are ones explicitly declared and have modifier 'static', and non-static ones are like static ones except for the keyword.

The important differentiator here is the keyword "static", or lack thereof. Modifier chosen is not very intuitive, but what it really means is this: non-static inner classes (including anonymous ones) have set of hidden variables added by compiler, passed via (hidden) constructor. And as a consequence, do not have zero-argument ("default") constructor -- even if it might appear one was being used by code.

So basically if you write something like:

  public class Outer {
   class Inner { // non-static
     public int getX() { return 3; }

what compiler actually generates is more like:

public class Outer { ... }

class Outer$Inner {
  private final Outer parent;

  Outer$Inner(Outer p) {
    parent = p;
  public int getX() { return 3; }

(and similarly for anything within "Outer" that code in "Inner" would access)

Why? Because this way code in Inner can actually access all members (including private ones!) within enclosing class; and in case of anonymous (inline) inner classes, even seemingly variables within scope (this is just smoke and mirrors -- final variables are passes as just more hidden constructor arguments).

And static inner classes are then just plain boring classes with no hidden baggage. In fact, they don't really differ from "secondary" classes (non-public classes declared in same source file as the main public class) by anything other than name which uses enclosing class for namespacing.

3. So about Jackson, inner classes... ?

The basic reason for Jackson's refusal to try use non-static inner classes for deserialization (serialization actually works fine) is because there is no general way to instantiate such classes -- there is no zero-argument constructor, nor @JsonCreator annotated other constructors or factory methods (or single-String-argument constructors, but I digress). Jackson can not instantiate them.

In theory one could handle this case if it was known what the enclosing parent class instance was. But realistically this is both complicated and unnecessary -- typically omission of "static" is either accidental, or incidental, and can be added to make things work.

Related Blogs

(by Author (topics))

Powered By

About me

  • I am known as Cowtowncoder
  • Contact me
Check my profile to learn more.