Phillip Pearson - web + electronics notes

tech notes and web hackery from a new zealander who was vaguely useful on the web back in 2002 (see: python community server, the blogging ecosystem, the new zealand coffee review, the internet topic exchange).

2003-6-5

Getting search to go

Well, it looks like I'm going to have to build the indices for this search engine offline (or at least outside the HTTP servicing routines). Either do it in a separate process (that either hangs around waiting for work to come its way or is called regularly via cron) or in another thread (started by the servlet when work becomes available).

Update: Incremental indexing is now working fine.

It looks like the convention with Java is to create resources in the servlet's init() method and store them in the ServletContext.

The weird thing is that this results in an implementation like this:

    public static final String CONTEXT_ATTR_ID = "nz.co.myelin.blogsearch.Indexer";
    
    public static Indexer getInstance(HttpServlet servlet) {
        ServletContext context = servlet.getServletContext();
        Indexer inst = (Indexer) context.getAttribute(CONTEXT_ATTR_ID);
        if (inst == null) {
            inst = new Indexer();
            context.setAttribute(CONTEXT_ATTR_ID, inst);
        }
        return inst;
    }

Which pretty much does the same as this, except is longer:

    private static Indexer _instance = null;
    
    public static Indexer getInstance() {
        if (_instance == null) _instance = new Indexer();
        return _instance;
    }

Can anyone tell me why one would prefer to store something as a ServletContext attribute over just shoving it in a static variable somewhere?

Update: Matt Goodall has the answer (see the comments). Using the ServletContext limits the scope to the current web app. (If the class lives in a library, using a static variable will result in sharing the instance across all web apps using the class).
... more like this: [, , ]