Using lazy initialization for the database in a web crawler is probably not worthwhile. Lazy initialization adds complexity and an ongoing speed hit. One case where it is justified is when there is a good chance the data will never be needed. Also, in an interactive application, it can be used to reduce startup time and give the illusion of speed.
For a non-interactive application like a web-crawler, which will surely need its database to exist right away, lazy initialization is a poor fit.
On the other hand, a web-crawler is easily parallelizable, and will benefit greatly from being multi-threaded. Using it as an exercise to master the java.util.concurrent
library would be extremely worthwhile. Specifically, look at ConcurrentHashMap
and ConcurrentSkipListMap
, which will allow multiple threads to read and update a shared map.
When you get rid of lazy initialization, the simplest Singleton pattern is something like this:
class Singleton {
static final Singleton INSTANCE = new Singleton();
private Singleton() { }
...
}
The keyword final
is the key here. Even if you provide a static
"getter" for the singleton rather than allowing direct field access, making the singleton final
helps to ensure correctness and allows more aggressive optimization by the JIT compiler.