Wednesday, January 31, 2007

Bag o' Crap

I got one!!! Well, three. This will be my second bag of crap. The last one contained an insulated beer pint glass, a rainbow-colored umbrella hat, and a camera bag.

Getting your hands on a bag of crap requires a number of strategies. They literally sell out in about 2 seconds. For example, the time it takes to click the link to buy 3 instead of 1 items might mean the difference between getting crap or nothing at all. I'd tell you more, but it would certainly interfere with my ability to score more crap in the future. ;)

Thursday, January 25, 2007

Lazy Loading Singletons

I woke up this morning thinking I knew all there was to know about lazy loading singletons in Java. Boy, was I wrong. Java doesn't cease to surprise me, even after all these years.

First, why would you want to lazy load a singleton? In production, you typically want to eagerly load all your singletons so you catch errors early and take any performance hit up front, but in tests and during development, you only want to load what you absolutely need so as not to waste time.

Before Java 1.5, I lazy loaded singletons using plain old synchronization, simple but effective:

static Singleton instance;

public static synchronized Singleton getInstance() {
  if (instance == null)
    instance == new Singleton();
  return instance;
}
Changes to the memory model in 1.5 enabled the infamous Double-Checked Locking (DCL) idiom. To implement DCL, you check a volatile field in the common path and only synchronize when necessary:
static volatile Singleton instance;

public static Singleton getInstance() {
  if (instance == null) {
    synchronized (Singleton.class) {
      if (instance == null)
        instance == new Singleton();
    }
  }
  return instance;
}
But volatile isn't that much faster than synchronized, synchronized is pretty fast nowadays, and DCL requires more code, so even after 1.5 came out, I continued using plain old synchronization.

Imagine my surprise today when Jeremy Manson pointed me to the Initialization on Demand Holder (IODH) idiom which requires very little code and has zero synchronization overhead. Zero, as in even faster than volatile. IODH requires the same number of lines of code as plain old synchronization, and it's faster than DCL!

IODH utilizes lazy class initialization. The JVM won't execute a class's static initializer until you actually touch something in the class. This applies to static nested classes, too. In the following example, the JLS guarantees the JVM will not initialize instance until someone calls getInstance():

static class SingletonHolder {
  static Singleton instance = new Singleton();    
}

public static Singleton getInstance() {
  return SingletonHolder.instance;
}
Why didn't IODH register in my brain sooner? I'm on the JMM mailing list after all. I think I had a mental block due to the fact that exceptions thrown in class initializers used to be difficult to debug, i.e. before nested exceptions. If I recall correctly, you would get an ExceptionInInitializerError (which would tromp the root exception) followed by a series of ClassNotFoundExceptions. Lazy loading from an application thread didn't suffer this problem.

Today, exceptions in static initializers are easy enough to diagnose--they appear nested in the ExceptionInInitializerError, so use IODH from now qualm free.

Update: Credit where credit is due, Effective Java (copyright 2001) detailed this pattern under item 48. It goes on to point out that you still have to use synchronization or DCL in non-static contexts.

I also switched singleton handling in my framework from synchronization to DCL and saw another 10% performance boost (compared to before I started using cglib's fast reflection). I only used one thread in my micro-benchmark, so the boost to concurrency could be even greater given that I replaced a heavily contended lock with a relatively fine grained volatile field access.

Fast Reflection

I replaced some critical reflective method and constructor invocations in one of my frameworks with cglib's optimized counterparts and saw about a 40% overall performance boost on Java 1.5. I only replaced the invocations, not the lookups, etc. I suspect cglib elides the security checks among other things, but I haven't dug too deeply.

Tuesday, January 23, 2007

Install PwdHash, now.

Right now. Cedric turned me on to it.

I assume most people use the same password for at least a couple web sites. I used to cringe every time I signed up for some random site and they echoed back my plain text password in an email. If someone happened across a password for one site, they could use it on another.

I used to mitigate the problem by using tiers of passwords. For example, I had one password which I changed often and used exclusively for work. On the other end of the spectrum, I had one password which I shared among all the random little sites and services which I didn't really care about securing. Coming up with and tracking a unique password for each site which I may never visit again was too much of a hassle.

PwdHash offers a much more elegant solution. I can always use the same password, but PwdHash hashes it with the site's domain before actually sending it. My real password never leaves my computer. Each site gets its own password, and there's no way they can figure out the password for a different site. To trigger PwdHash, all I have to do is press F2 before typing in my password.

I don't have to maintain a password repository across computers (that would be another security risk). If I'm on a computer where I can't install PwdHash, I can always go to their site and cut and paste the hashed password.

It's such a simple but effective idea. I hope other clients such as instant messengers pick up on it. In the mean time, I can always cut and paste.

Running your electric meter backwards...

Slashdot linked to an article on residential solar power. We have the same setup: solar panels on the roof, no battery. If we generate more power than we consume (as is often the case), the excess power goes back into the grid and the electric company credits us for it. I think my highest electric bill was $8 last year. We ran the window AC unit nearly non stop; then again, we live in northern California, so it doesn't get too hot.

The little hacker in me loves the fact that I can connect to my solar system with a serial cable and monitor the throughput from my computer. I've been trying to come up with a cost effective way to do so wirelessly. I wonder if I can hook a serial cable to a WRT54G... so many projects, so little time.

The Java Posse's 100th Episode

Carl

A momentous event to say the least. Enjoy the photos, and keep an eye out for the podcast. At the risk of getting on the posse's bad side (I can't keep this tidbit to myself), you have to check out their app of the week Goggles, a Google Maps flight simulator.

Monday, January 22, 2007

Javadocing Nested Classes

Javadoc seems to include static nested classes in the package-level Javadocs but not inner classes (classes which can't stand alone and require an instance of their enclosing class). Keep this in mind if you must expose a class but you also want to semi-hide it within another class's documentation so as not to clutter up the package-level documentation.

I recently used this trick for a mini-DSL. I have various inner classes which I return depending on the context; doing so ensures we only expose relevent commands to the client. Making these classes inner instead of static nested prevents them from distracting from the single entry point class in the package level Javadocs.

Subversion Mime Types

If you want to serve HTML files, images, etc., directly out of your Subversion repository, you should configure your client to set mime types automatically based on the file extension when you check in. I sometimes use this to host online Javadocs for example.

Sunday, January 14, 2007

What's this guy thinking?

Glenn Lurie, Cingular's president of national distribution, bragged to journalists about how Cingular made Apple bend over with the new iPhone and impose a bunch of toxic-to-consumer restrictions (typical AT&T fashion). My favorite quote: "there are bad guys out there that unlock phones." Steve won't be happy.

Friday, January 12, 2007

Property Objects

Matthias wonders why we don't just use objects to model properties. Great question. Internally circumventing any behavior you've added and accessing the underlying field wouldn't be as straightforward, but I'm not sure that's such a big deal. This would certainly make sharing logic between properties a lot easier. I can't think of any reason you'd want to add behavior around dereferencing the property object itself, so I don't have a problem with exposing it as a public field. This uses up a little more memory and isn't quite as straightforward, but I think I still like it.

Wednesday, January 10, 2007

Types vs. Instances

How often have you said "object" when you really meant "class?" Martin just posted an interesting piece on homonyms. The most interesting conclusion: disambiguating terms can actually result in more confusion.

Dave doubts the Apple TV

Dave: "Don't expect me to gush, I think it's the wrong way to go, and not because of its resolution."

I'm interested to hear what he has to say.

I on the other hand predicted this two years too early (the Mac Mini came out instead), and I think it's the absolute right path. Downloading is easier than recording, especially if the shows download automatically (no missing the final 5 minutes because a show runs over or your DVR hiccups). I'm happy with the resolution, too.

Tuesday, January 09, 2007

What does the iTunes Paramount deal mean?

IMG0001

Star Trek movies!!! I'm literally pissing my pants with excitement. I can't wait until my Apple TV comes. You know I had a Star Trek wedding, right?

802.11n for my Mac Pro

Remember how I was trying to get 802.11n working on my Mac Pro? According to Apple's site, I at least had the hardware all along:

These Mac computers support 802.11n in the new AirPort Extreme Base Station using the included enabler software:

  • iMac with Intel Core 2 Duo (except 17-inch, 1.83GHz iMac)
  • MacBook with Intel Core 2 Duo
  • MacBook Pro with Intel Core 2 Duo
  • Mac Pro with AirPort Extreme card option
The new Airport Extreme Base Station (which I just ordered) comes with software to enable my Mac Pro's 802.11n support. I also ordered the Apple TV. I'll be streaming HD video to my bedroom TV in no time.

Sunday, January 07, 2007

Piranha Plant

I started a Wii blog. I rarely (if ever) played games before the Wii. It's perfect for a casual gamer like myself. I didn't think Nintendo had it in 'em, but they seriously innovated and left Sony in the dust. We took the Wii with us to St. Louis over the holidays. My father in law couldn't get enough Wii Sports. We even had Dagny playing the boxing game at one point (you don't need the buttons), and she knocked her grandpa out.

As you can see, I utilized Blogger's new custom domain feature for piranhaplant.com.