Saturday, May 28, 2011

stackoverflow - 20k rep

Four months after crossing the 10k milestone, I've now achieved a reputation of 20k on stackoverflow! The following table shows some interesting stats on my time at SO:
Title 0-10k 10-20k Total
Questions answered 546 376 922
Questions asked 46 1 47
Tags covered 609 202 811
Badges 35
(2 gold, 10 silver, 23 bronze)
14
(0 gold, 4 silver, 10 bronze)
49
(2 gold, 14 silver, 33 bronze)
As I mentioned in my previous post, I have really enjoyed being a member of stackoverflow. For me, it has not simply been a quest for a high reputation, but more about learning new technologies and picking up advice from other experts on the site. I like to take on challenging questions, rather than the easy ones, because it pushes me to do research into areas I have never looked at before, and I learn so much during the process.

It's hard juggling work and stackoverflow. The only times I get to use it are during the weekends and in the evenings after work. Most of the questions have already been answered by then! However, I still like browsing the questions and checking out the answers.

30k, here I come!

Saturday, May 14, 2011

Lazily Instantiate a Final Field

Java only allows you to instantiate final fields in your constructor, like this:
public class Test{
  private final Connection conn;

  public Test(){
      conn = new Connection();
  }

  public Connection getConnection(){
      return conn;
  }
}
Now, let's say that this field is expensive to create and so you would like to instantiate it lazily. We would like to be able to do something like the following (which won't compile because the final field has not been initialised in the constructor):
//does not compile!
public class Test{
  private final Connection conn;

  public Test(){
  }

  public Connection getConnection(){
      if(conn == null)
          conn = new Connection();
      return conn;
  }
}
So, there is no way to lazily instantiate a final field. However, with a bit of work, you can do it using Memoisation (with Callables). Simply wrap your field in a final Memo as shown below:
public class Memo<T> {
  private T result;
  private final Callable<T> callable;

  private boolean established;

  public Memo(final Callable<T> callable) {
      this.callable = callable;
  }

  public T get() {
    if (!established) {
      try {
        result = callable.call();
        established = true;
      }
      catch (Exception e) {
        throw new RuntimeException("Failed to get value of memo", e);
      }
    }
    return result;
  }
}

public class Test {
  private final Memo<Connection> conn;

  public Test() {
    conn = new Memo<Connection>(new Callable<Connection>() {
      public Connection call() throws Exception {
        return new Connection();
      }
    });
  }

  public Connection getConnection() {
    return conn.get();
  }
}