Fast Synchronized Initialization

  1. It is often the case that we don't want to construct an object until it is first needed. For example, after downloading the font file cmr10.300pk, we may not want to immediately decompress the character data for each character of that font. It will take too much time and memory, and it is unlikely that every character will be needed right away.

  2. The natural way to delay construction is to store a NULL pointer in place of the object, and test for NULL before using the object:
    static Object object;
    
    void useObject( ) {
        if( object == NULL )
            object = new Object( );
        
        // use object now
    }

  3. This scheme fails when there may be multiple threads accessing the object. This may occur if an applet is referenced from more than one document, or if, as in IDVI, documents are being loaded by separate threads.

    The obvious solution is to make the useObject method synchronized:

    static Object object;
    
    synchronized void useObject( ) {
        if( object == NULL )
            object = new Object( );
        
        // use object now
    }

  4. Synchronization is slow (5-10us, even when running inside of a JIT environment). If you might need to call useObject or methods like it thousands of times per second, then the overhead is quite large. The trick is to avoid synchronization once the object has been constructed, while still using a synchronized method to prevent multiple copies from being constructed:
    static Object object;
    
    void useObject( ) {
        if( object == NULL )
        	constructObject( );
        
        // use object now
    }
    
    synchronized void constructObject( )
    {
        if( object == NULL )
            object = new Object( );
    }

  5. This idiom is pervasive in IDVI. It is used for constructing decompressed character data, for creating Image objects to represent individual characters, and for creating Color objects used to represent the colors used in drawing a rule, for example.

    The idiom is used when an object may or may not ever need to be constructed, but may be used many times once it is constructed. Decompressed character data is probably the best example. If a symbol appears once in a document, it will likely appear many times.