Lazy Loading For Mere Mortals
August 23, 2008
Easily the #1 mistake people make when using Warp Persist is they forget to start their PersistenceService, which is the API that abstracts the Hibernate SessionFactory. The plan for the next release is to start the PersistenceService lazily. Thus the first time a SessionFactory gets accessed, we will load it for you if you haven’t called PersistenceService.start() yet. This is a simple change that will help you get your project going in no time.
The obvious choice for implementing this type of lazy loading as of Java 5 is Double-Checked Locking. But after coding it up for the Hibernate SessionFactory, I realized I would have to do the same for the JPA and DB4O support. Given the relative complexity of DCL, that kind of sucks.
But then I remembered something Bob Lee said on Twitter the other day:

Bob Lee on Twitter
The man has a point.
I decided to roll our own utility class to lazily load object references. So I opened up the bible (Effective Java, 2nd edition) to look for the original pattern, and there it was. Page 283:
private volatile FieldType field;
FieldType getField() {
FieldType result = field;
if (result == null) { // First check (no locking)
synchronized(this) {
result = field;
if (result == null) // Second check (with locking)
field = result = computeFieldValue();
}
}
return result;
}
Scary. Now, there is no way we can reduce the size of that code much, but as it turns out we can make it a lot simpler to use. I called it LazyReference, here’s an example usage:
private final LazyReference<SessionFactory> sessionFactory =
LazyReference.of(new Provider<SessionFactory>() {
public SessionFactory get() {
// code to create SessionFactory
}
});
To use this code, you just call sessionFactory.get(), and it will handle the lazy loading for you. Even if you are a Java master, there is no reason for you to repeat that complicated DCL code ever again. Enjoy!
Guice’s toProvider Sometimes Considered Harmful
July 21, 2008
Perfection is what I wanted. Writing code examples for a book is harder than you think; Not only does the code need to be right, it also needs to be short and lightweight. Don’t involve API’s you don’t need, don’t create types if you can do without them, that sort of thing.
So I was nearing the handoff deadline and I was going over my code examples. I corrected some and tried to shorten others. For example, in the Chapter 6 example I saw the following code, which I used to abstract session handling from my view logic*:
public class UserTokenProvider implements Provider<UserToken> {
@Inject private HttpSession session;
public UserToken get() {
synchronized (session) {
return (UserToken) session.getAttribute(UserToken.KEY);
}
}
}
public class WebModule extends AbstractModule {
protected void configure() {
bind(UserToken.class).toProvider(UserTokenProvider.class);
}
}
Surely I wasn’t going to list two classes just for a simple provider, so I quickly decided to get rid of the extra class as follows:
public class WebModule extends AbstractModule {
protected void configure() {
bind(UserToken.class).toProvider(new Provider<UserToken>() {
@Inject private HttpSession session;
public UserToken get() {
synchronized (session) {
return (UserToken)session.getAttribute(UserToken.KEY);
}
}
}); // no scope!
}
}
Now, months later it struck me. This is wrong! (and arguably even less readable) In the shortened version I am now giving Guice a provider instance instead of a provider type. Using that toProvider overload is comparable to using Guice’s toInstance: it will just reuse that instance for all requests to that Key, disregarding all scopes. And when I say all scopes, I mean all scopes. It also ignores the default “no scope”. Using the default scope, Guice will create an instance each time that Key gets requested. However, if you bypass all scopes with toInstance or the toProvider instance overload, Guice will simply reuse your instance.
In my example I was depending on the fact that the HttpSession injected in the provider was always going to be the right one. In the original example it worked as expected. I gave Guice a provider type, and used the default “no scope” so that a new instance would get created for each incoming HTTP request. Guice would inject the right HttpSession instance depending on the request.
Because the second example uses toProvider with an instance instead of a type, it behaves radically different. Ignoring “no scope”, Guice will just inject the first HttpSession instance it finds and from then on it will leave that provider instance alone (a scope widening injection, if you will). Any subsequent requests, from possibly different sessions, will reuse that instance, leading to session corruption and a significant security risk.
Needless to say, I have fixed my code example and published the update to Apress.
Save yourself from such an embarrassment: Remember that toInstance and the toProvider instance overload ignore all scopes, including “no scope”. Avoid using them: use asEagerSingleton to load instances eagerly. Only use these short cuts to fit code on a slide, or in the case of toInstance, to bind constants with better type safety.
* I am not using Guice’s session scope because the UserToken is used as an authentication token in the session. Using scopes, Guice might end up creating a security token for you when it gets requested, which is obviously not what you’d want.
Guice Productivity
May 8, 2008
Plugin hell: we’ve all been there. Large frameworks like Spring, Seam, … often require IDE plugins for you to be productive. That’s cool. But installing plugins and getting them to work right, at least when using Eclipse, is utter, utter torture.
Some of them don’t work as advertised. Some of them don’t work with your particular Eclipse version. Some of them make others crash.
What’s refreshing about a framework like Guice is that you don’t need all of that. Because Guice is an all-Java framework, you don’t need to install any IDE plugins. Your Java IDE _is_ the plugin. There’s years and years of hard work at your fingertips, so why not work _with_ it instead of working against it? Developing with Guice feels like coming home.
Recently I cooked up a screen cast that shows off Multibindings, a much anticipated Guice 2.0 feature. As I mention in the beginning, I use some IDE templates for my Guice development, and you’ll probably agree with me that it shows. I’ll share those with you in a minute. But first, my brain fart of the day: Know and learn your IDE, and expect the same from the frameworks you use. 70% of the code generation refactorings/templates in my Multibindings screencast are built right into the IDE. And 100% of them are configurable out of the box.

Here’s what I’ve currently set up. This configuration is Eclipse specific, but I’m sure IDEA and others have similar features.
- Static imports: Window => Preferences => Java => Editor => Content Assist => Favorites.
- This thing is pure gold. It allows you to specify types that have static methods on them, so that Eclipse can index them and suggest static imports for methods you often use. This feature is an awesome time saver for things like Google Collections, but also for JUnit tests and not surprisingly Guice. For Guice I’ve added the
Matchersclass (AOP) and theNamesclass (eeeviiiil).
- This thing is pure gold. It allows you to specify types that have static methods on them, so that Eclipse can index them and suggest static imports for methods you often use. This feature is an awesome time saver for things like Google Collections, but also for JUnit tests and not surprisingly Guice. For Guice I’ve added the
- Templates: Window => Preferences => Java => Editor => Templates. Using this simple IDE feature, all boilerplate is just a
CTRL+SPACEaway. Important: press save (CTRL+S) and Organize Imports (CTRL+SHIFT+O) after you complete a template. This makes sure that you have all the needed import statements. - Binding Annotations: creating these is tedious and error prone. One approach is to copy-paste the boilerplate, the other is to have a template. I’ve set one up that automatically inserts the annotation headers you’d usually want.
Injectorcreation: I tend to run a lot of “experiments”, also known as the “Launching Main893.java” syndrome. So next to the binding annotation header, I’ve also set up a template that creates me an Injector with an inlineAbstractModule. Also works great for demos.- Constructor generation: simple template that creates the default constructor and puts your cursor in between the parenthesis so you can immediately start typing.

Other notable built-in features are CTRL+1 (Quick Fix) on constructor fields, which can create private final instance variables for selected constructor arguments, and typing a method name and hitting CTRL+SPACE to override or implement that method.
Now without further ado, here are some of my templates.
Mapped to ‘gah’ (as in Guice Annotation Header):
@Retention(RetentionPolicy.RUNTIME) @Target({ElementType.FIELD, ElementType.PARAMETER}) @BindingAnnotationMapped to ‘gin’ (as in Guice INjector and booze):
Injector i = Guice.createInjector(new AbstractModule() { protected void configure() { ${cursor} } });Mapped to ‘constr’ (creates a constructor and sets the cursor where it needs to be):
public ${enclosing_type}(${cursor}) { }
Enjoy!
DollarMaps: Easy Map Creation for Java
April 6, 2008
Inspired by GQuery’s syntax, I hacked up some code that uses a similar, dollar sign based syntax for creating Java Map instances. And I have to say that it flows really nicely. But first, let’s “respect the classics” .
Map<Integer, String> map = new HashMap<Integer, String>();
map.put(1, "one");
map.put(2, "two");
map.put(3, "three");
// iterate over all the entries
for (Entry<Integer, String> e : map.entrySet())
System.out.println(e.getKey() + " " + e.getValue());
So, there are three things to notice here.
- The repeated type parameters on the first line
- Having to use three lines of extra code to get the items in
- Having to use getKey() and getValue() in the iteration
If you didn’t know yet, most of these issues can be solved by using Google Collections. But besides that, I think the dollar sign based syntax, which I called DollarMaps, is slightly more elegant than the usual “let’s-do-some-type-inference” factory method.
Creating a HashMap:
Map<Integer, String> map = $(1,"blah1")
.$(2, "blah2")
.$(3, "blah3").asHashMap();
Iteration:
for(Entry<Integer, String> e : $(1,"blah1").$(2, "blah2")) {
System.out.println(e.getKey() + " " + e.getValue());
}
You can even take iteration further if both the key and the value have the same type. I tried some things out and came up with the double dollar sign syntax to enforce that type rule. So easier, array-based iteration:
for(String[] s : $$("1","blah1").$("2", "blah2").asEasy()) {
System.out.println(s[0] + " " + s[1]);
}
I did not run any performance tests (I am creating a 2-element array for each entry).
Anyway, I’ll have this up for grabs at my Google Code project. For the impatient, here’s the download link. Feedback appreciated!
Guice Book Released!
March 28, 2008
I should really get some sleep, but I can’t wait to get the word out. The book I was working on “Google Guice: Agile Lightweight Dependency Injection Framework” has gone live! It’s available in ebook and print-on-demand formats.
Apart from the title, I think the book reflects the fact that I’m a no-nonsense guy. I’m just like you, interested in new technology and I want to see this Guice thing in action. They did that with dependency injection? Hell yes; let’s see why they did it, and who they killed to get there (just kidding :-)).
So, months later I look on Amazon, and see this:

You can get my humble work together with the best Java book ever. That alone was so worth it :-)
Thanks again to Apress, Bob, Dhanji and the Guice community: I couldn’t have done it without you.
Guice, Spring 2.5 and Finding Mistakes Early
March 15, 2008
Yesterday I gave a talk on Guice at the Profict Wintercamp! The goal of the event was to look at how Guice changes the Spring landscape by letting both sides present their framework. From the Guice side there was me (thanks Bob, for not being able to come! ;-)), from the Spring side there was Alef Arendsen.
Surprisingly, there was only one Guice user present! They should have given us an “I went to the Profict Wintercamp and I lived.” t-shirt. :-) No seriously, I had a great time and enjoyed talking to other developers and the guys from SpringSource. Let’s hope I convinced some people to take a look at Guice!
Right before the talk I had some time to spare, so I quickly threw together a Guice demo application that I then re-implemented using the Spring 2.5 new annotation-driven configuration options. Next, I decided to take a look at how Spring compares with Guice in terms of error detection and error handling. This has always been one of Guice’s strengths, but it’s also one of those “nice-to-haves”. It’s like a cell phone. You don’t miss it until you have one. All those Spring users don’t know what they are missing!
The example code can be found here, and the error handling comparison can be found here. I’ll upload the presentation and the packaged source code soon. Enjoy!
The Last Lecture
February 5, 2008
A Goldfish’s Memory of Javapolis 2007
December 13, 2007
Conference, day 1-2
- The JavaFX programming model is no match for Flex’s or Silverlight’s
- Bruce Eckel doesn’t look like Bruce Eckel
- Googlers, Googlers, Googlers (carry an Apple, Apple, Apple)
- Neal Gafter has a hat glued to his head
- Bob “natural currency” Lee is a nice guy and an excellent presenter
- Ola Bini got in the country, despite looking like a serial killer
- The Java Posse recording was fun, but the audio was terrible
- Josh Bloch is always right, even if he’s not
- Effective Java Forever
Guice Book
December 13, 2007
I’m writing a book on Google Guice, the notorious DI framework created by Bob Lee. I’ve been active in the Guice community for quite a while now, and I have to say that it’s an honor to get the opportunity to write about one of the most innovative Java frameworks out there. Now that it’s been published on Amazon, I feel like I’ve reached the point of no return. The world knows, so I’d damn well better make sure that I deliver some quality. So far I’m having a blast, so perhaps I’m still in Ted’s phase two. :-)
On a related note, I enjoyed talking to Bob at Javapolis today. On popular demand he took the advanced route for his Guice talk, which I think was appropriate. Too bad he didn’t have enough time to go through the example though. I was pleased to learn that much of what he talked about already made it into the book, in some form. Which must be a good thing, right? Anyway, one more day at Javapolis, and then back to work. :-)
Wish me luck. I’ll try to make sure I won’t need it. ;-)
Guice Debug Output
December 8, 2007
Guice has a dirty little secret: it logs timing information to its JDK Logger. A while ago I created a simple utility class for myself to enable or disable the logging of Guice’s debug output to the console. Here goes nothing.
/**
* Enable or disable Guice debug output
* on the console.
*/
public class GuiceDebug {
private static final Handler HANDLER;
static {
HANDLER = new StreamHandler(System.out, new Formatter() {
public String format(LogRecord record) {
return String.format("[Guice %s] %s%n",
record.getLevel().getName(),
record.getMessage());
}
});
HANDLER.setLevel(Level.ALL);
}
private GuiceDebug() {}
public static Logger getLogger() {
return Logger.getLogger("com.google.inject");
}
public static void enable() {
Logger guiceLogger = getLogger();
guiceLogger.addHandler(GuiceDebug.HANDLER);
guiceLogger.setLevel(Level.ALL);
}
public static void disable() {
Logger guiceLogger = getLogger();
guiceLogger.setLevel(Level.OFF);
guiceLogger.removeHandler(GuiceDebug.HANDLER);
}
}
Output looks something like:
[Guice FINE] Configuration: 51ms [Guice FINE] Binding creation: 53ms [Guice FINE] Binding indexing: 0ms [Guice FINE] Validation: 131ms [Guice FINE] Static validation: 0ms [Guice FINE] Static member injection: 2ms [Guice FINE] Instance injection: 2ms [Guice FINE] Preloading: 1ms
Listen to the Logger, it’s making sense. Guice is fine! :-)

