Self-bound generic types and why do they matter

3 comments

There are some good people who appreciate the real value brought by Generics. But even fewer actually know or fully understand what purpose do self-bound generics really serve. The expression looks quite hazy at first and might make your head go spin if you begin wondering with utterly different but naturally occurring thoughts that may come to your mind while looking at the expression. It looks like this:

interface FooType<T extends<FooType<T>>

Looks like a mirrored expression which absolutely gives you no idea how deep the rabbit hole goes. Some people complain that generics have destroyed the simplicity of Java. But, I would argue that any useful language tends to grow a bit more complex as it goes through a constant process of evolution.

So, let’s see how in this world is this confusing recursive expression any useful at all. Some of you must have seen this expression being used in java.lang.Enum type-definition like this:

abstract class Enum<E extends Enum<E>>

Some of you might be thinking that simply Enum<E> would’ve sufficed for better type-safety but it turns out that controlling the implementing types or sub-types, sometimes, becomes necessary. For those times, the self-bound or recursive generic types come to the rescue.

To imagine what kind of control do self-bound generic types provide to the super-type, just think about the bounded generic types (non recursive) and what’s their significance. For example Foo<T extends SomeType> means that whatever type Foo holds, has state-properties and attributes defined by ‘SomeType’. So intuitively, a self-bound generic type would simply mean that all the state-properties and attributes would be defined by the holding type itself. Now this is the key to understand the real significance behind self-bound generics. The famous getThis() technique would also work without self-bound generic types (which is contrary to what some people believe) but when, for example, you are trying to encapsulate the behavior (a.k.a Strategy pattern from GoF) the self-bound generic types bring a great deal of flexibility.

Double-check Locking pattern is not broken any more

5 comments

It’s been a long time since Jdk 1.5 came along (it has now even passed it’s general support lifecycle) and brought many good changes. Infact, I heart all of them. One of the mature enterprise aspects of using Java as a platform is the promise of backward compatibility. The biggest example is choosing type-erasure for generic types (and keeping same Collections package too ;) rather than going for old-school reification and breaking the promise. From this point of view, the biggest achievement was the introduction of a clean and consistent memory model (JSR 133). Before that, almost all concurrency code written in Java was at the mercy of chance and was thus broken.

Among the older times, to create a lazy singleton, some people came up with a pattern called “Double check locking”. It went like this:

public class Foo {
  private Helper helper = null;
  public Helper getHelper() {
    if (helper == null)
      synchronized(this) {
        if (helper == null)
          helper = new Helper();
      }
    return helper;
  }
}

It would let you get rid of ‘synchronize’ing the complete method block and would lazily create the singleton instance. But the simple problem was… it was actually broken for any optimizing VM or shared-memory multiprocessor system. Why because an optimizing JVM is free to do out-of-order writes.

You could still create a singleton (for JVM) instance simply this way:

public class Foo {
  public static Foo instance = new Foo();
  private Foo() {}
}

But for a bean-scoped singleton (means singleton but only for a particular object) you couldn’t choose this way and all you were left with was the same broken DCL pattern.

Fast forward to the time when JSR 133 (a Java memory model standard) was being considered and ‘volatile’ keyword was finally gonna get some work to do :) So, now if you use ‘volatile’ modifier for the ‘Helper’ instance variable, it’ll cause the famous ‘happens-before’ relation to come into play and won’t let the JVM optimization to step on your shoes. You can safely use the old DCL pattern with ‘volatile’ keyword like this:

public class Foo {
  private volatile Helper helper = null;
  public Helper getHelper() {
    if (helper == null)
      synchronized(this) {
        if (helper == null)
          helper = new Helper();
      }
    return helper;
    }
  }

Still if this looks ugly to you, don’t feel bad because the JSR 133 also brought the thread-safety guarantee for the class loader and enabled the “Initialization on demand holder” pattern (one of my favorites) to come into existence to serve the cause of singleton.

public class Foo {
  private Foo() {}
  public static Foo getInstance() {
    return FooHolder.instance;
  }
  private static class FooHolder {
    private static Foo instance = new Foo();
  }
}

And here you go. A lazy and clean pattern to create a JVM-scoped singleton instance.
Never forget that you still have to resort to the, now-fixed, DCL pattern to create a bean-scoped singleton. But at least it’s not broken when you use it on a standard JDK 1.5+ JVM.

I hope this blog post busts a famous myth “DCL is broken”. It only _was_ back in the dark days of pre-jdk1.5 which was quite ages ago. Long since, it’s been working correctly, although you now have a cleaner way called IODH pattern.

P.S: I din’t touch on the aspect of utilizing an enum to create a robust Singleton (as mentioned in Effective Java) since this post was primarily a myth buster on DCL pattern. Let that be the topic of some other post.

Update 1: I think I forgot to mention that ‘volatile’ by no means guarantees atomicity. It’s also a common myth. For more details, read this.

Modular enterprise builds with Gradle

no comments

It’s been a handful of time i’ve stayed away from blogging. Partly because of work, partly because of laziness. But hey, these days i’ve got my hands on a project I have to design and implement. And trust me, it’s not only one of the best things to do, it’s also a bit tough since you have to decide and tradeoff many things at various stages of design. Powerful yet flexible design requires the usage of tools belonging to this very nature when it comes to the implementation.

One of the most important assets of an engineer are his build tools. We don’t see many flame wars around build tools (like we see around IDE’s etc) because there are only a couple of them which could actually take off. Ant took the world by storm while Maven introduced strict conventions to provide flexibility. Now, you must have got the idea what i’m talking about.

Recently, when I came to know about Gradle, it looked appealing to me. Although I was pretty concerned about the usage of Groovy and Groovy based DSL and all the unnecessary magic it would bring. But I quickly realized that my concerns might have aroused due to the usage of XML in build tools for ages. So, I took the red pill to actually see myself, how deep the rabbit hole goes and to my surprise, Gradle started appearing to be the thing I was looking for to cleanly implement the modular design I had perceived.

Gradle doesn’t impose itself on you and never interferes with your design choices. It infact brings the best of both Ant and Maven to the table, and lets you decide what to do. Of course life becomes much easier when you follow trivial conventions like source and test directory structures and all. For the basic stuff, nothing beats Gradle’s User Guide.

Quite some time ago, I had built a toy project about Spring/Hibernate integration with Maven build and had written a 3-part blog series tutoring it step-by-step. To show off how that thing could be designed in modules without any pain and how build mechanism could be improved, I brought Gradle to the same project. I’ve open sourced the scripts and some trivial clock-ticking stuff at GitHub. I hope it proves fun and helpful to you. The modules are separated w.r.t layers like:

  • Web
  • (JSF 2 views and Spring MVC @Controllers)

  • Service
  • (Spring @Service components and @Aspect Pojo’s)

  • Domain
  • (Spring @Repository and Hibernate Pojo’s)

If you simply execute:

gradle :web:war

Gradle will follow the dependency graph that’s, among application modules is simply (Web -> Service -> Domain) and will jar up the dependencies with their dependent jars upto the Web module which will actually war up and you can give it a try with Jetty container:

gradle :web:jettyRunWar

You may notice that already-built-source won’t build again and everything can be flexibly achieved using Gradle plugins. That’s the beauty behind this tool.

One-line property accessors with live templates

6 comments

Like many, I’ve always been bothered with trivial multi-line getter/setter methods while writing POJO’s. When you use an IDE, like Intellij Idea, you usually auto-generate those accessors. But the problem is that it’s such a trivial thing that IDE-makers don’t think of letting their users customize these things for themselves.

But hey, Intellij always surprises you with it’s powerful features you won’t find anywhere else (or atleast as good and proficient). Right when I was looking for such a thing, Emmanuel Bernard made a blog post on how you can achieve this in Intellij using it’s powerful Live Templates. He created his template, the way he preferred, obviously. I went on a step further to customize it my way and save another keystroke. I’ll show you how:

1) Go to the Settings -> Live Templates and add a new live template.
2) I named it ‘acc’. Check marked Java as scope and added the following template:

private $TYPE$ $lowername$;
public $TYPE$ get$UpperName$() { return $lowername$; }
public void set$UpperName$($TYPE$ $lowername$) { this.$lowername$ = $lowername$; }

3) Then click on the ‘edit variables’ and set the UpperName’s expression to ‘capitalize(lowername)’
4) You can save another keystroke (you’ll see how) by marking UpperName’s ‘skip if defined’ check.

After you make this template, come back to your Java file in Intellij, type ‘acc’ and hit the tab key and all you have to do is write the type and name of the field and you get one-line getter/setter methods auto-generated for you very cleanly.

Mapping results for unmapped entities

17 comments

A while back, I got into trying out iBatis while refactoring a legacy module’s persistence layer. It was really fun working with a well respected persistence solution and going through situations where iBatis might give you an edge over a more rich persistence solution like Hibernate. One of the good impressions on me were the simplicity and ease with which you could marshal native SQL query results into a Java type without having to worry about their entity mapping. Yes, ResultMap is the name of the thing I am talking about.
Suddenly, after a while, when I got busy cleaning up an old codebase (persistence code but with Hibernate this time), I found myself lost when I saw Object[]‘s everywhere and their magic index accessor numbers which give you no idea what is being taken out of those marshaled query-results. To elbow out those Object[]‘s and introduce type-safe result marshaling you need a container class with required fields and public accessors.

IBatis’ ResultMaps help in these situations a lot. If you’r thinking of hibernate DTO’s or maps then forget about them because practically you can’t have all the multi-arg constructors with different combinations of internal fields. It would rather kill the purpose of cleanup itself. Another solution was to use the named queries such that the results would fill up your mapped entities like this:

<sql-query name="getAllMyUsers">
    <return alias="usr" class="mine.dao.domain.User"/>
    select
    usr.user_id as {usr.id},
    usr.first_name as {usr.firstName},
    usr.last_name as {usr.lastName},
    usr.email as {usr.email}
    from User usr
  </sql-query>

But it only helps when you have a result type that is a mapped entity. If it isn’t mapped, then you’r out of luck.

Upon digging deeper, I found out that Hibernate wouldn’t disappoint you. For situations like this, Hibernate Transformers come to the rescue. You simply tell hibernate the scalar return column and it’s type and on the query object you can call the result transformer like this:

//inside DAO/repository method
@SuppressWarnings("unchecked")
List<UserProps> props = (List<UserProps>)session.getNamedQuery("getAllUsers")
          .setResultTransformer(Transformers.aliasToBean(UserProps.class))
          .list();

While your sql query and it’s results (unmapped entity) would look simple:

<sql-query>
  <return-scalar column="id" type="java.lang.Long"/>
  <return-scalar column="firstName" type="java.lang.String"/>
  select
  usr.user_id as id,
  usr.first_name as firstName
  from User usr
<sql-query>

And of course you need to hold your results into some container:

public class UserProps {
  private Long id;
  private String firstName;
  //...no-arg constructor
  //...public accessors
}

And bingo! you get your sql query results marshaled into a collection of UserProps so you don’t have to use those ugly Object[]‘s and magic index accessor numbers anywhere at all while making your code clean, readable and type-safe.

The only thing I missed was strong type-safety in hibernate’s API. You shouldn’t need to cast it and suppress the compiler-generated type-safety warnings if the API respects parametrized types. I hope that Hibernate will address type-safety concerns with the future releases of their API.

Selenium on TestNG

16 comments

A very important part of software testing is Acceptance testing. Either developer should be doing it (like unit tests) or not should better be left for some other post. The important thing is, acceptance tests do matter, they test something that your user is going to perceive when she uses your application. Like every other type of testing, the more acceptance tests’ coverage gives more quality. When it comes to growing number of tests, we need a helping hand from test suites we could rely on. To automate acceptance testing for web apps Selenium comes in as a very handy tool. More can be learnt about Selenium over here.

Selenium has a rich set of commands to test almost everything inside the DOM and it has drivers for Java, C#, Ruby, Python, Perl etcetera…. wait! did I say Java? Oh cool! if it has a Java driver, then we can use our favorite testing framework known as TestNG (which is a great framework to do end-to-end testing) as a test runner to execute our selenium test cases written in Java. Doesn’t that sound awesome? All the goodness of Selenium being handled through TestNG.

With this approach in mind I went on investigating how to integrate both frameworks. Now Selenium can create a whole test suite of individually grouped cases which we can transform into corresponding TestNG test classes but to run every TestNG class we can’t instantiate expensive resources like browser etcetera every time. And on the other hand we need to have some way to run our test cases in a determined sequence to test our application’s flow because most of the time we have to test the integration among different modules of application. For example, Module A makes up some data on which Module B depends and so on.

I’ve addressed these two major concerns successfully and am now open sourcing my work which might give a small (modestly speaking ;) helping hand to someone. You can find the source in my GitHub repository as a project named SeleniumOnTestNG.

Building Android kernel from source

4 comments

So, you wanna build the Android kernel from source. Great, that’s a cool thing to do. I assume that you’r already using a Linux distribution (and probably Ubuntu). If not, go get Ubuntu first. More: Read the rest of this entry…

Gwt-coded Presentations

6 comments

Yes, a presentation but not built on Google Docs(I din’t consider Powerpoint or OpenOffice since I love web as a platform). I was just looking for some fun time so I thought maybe I should _code_ my slides instead of writing them. More: Read the rest of this entry…

Unit and Integration Testing with TestNG

8 comments

I am a big fan of developer testing. You begin to realize the real benefits of testing, six months down the road (or maybe a year) when your code-base starts growing, your project has more features than before and suddenly you come across a bug. You write your patch and start thinking how would you test that patch and make sure that:

I) It actually solves the issue
II) It doesn’t shake already working features
III) It doesn’t, by any chance, introduce a new bug More: Read the rest of this entry…

Spring 3 integrated with Hibernate Part-C

23 comments

After going through Part-B of this tutorial series, you must have a working console application built on Spring 3 and Hibernate and by now you must have got a good idea of how Spring can manage your database transactions by encapsulating persistence-layer based transactions behind the curtains. Yes, behind the scenes Spring delegates transactional handling to [in our case] Hibernate and exposes an easy-to-use transaction facade for us. Since Spring has been in such a widespread use that if you follow old-school DAO pattern to encapsulate Hibernate POJO’s then you don’t even need to provide transaction details, instead you just extend one of the Spring provided DAO templates (HibernateTemplate in our case), override the CRUD methods and Spring will handle transaction details internally. But it poses two serious drawbacks of vendor lock-in and tight-coupling. More: Read the rest of this entry…