Women in Technology

Hear us Roar



Article:
  Lazy Loading with Aspects
Subject:   beware of lazy loading
Date:   2004-06-28 11:56:12
From:   pk2
your code examples are not thread-safe. here's an article that tells you a bit more on how lazy loading can be dangerous in multi-threaded environments: Double-checked locking and the Singleton pattern
Full Threads Newest First

Showing messages 1 through 2 of 2.

  • beware of lazy loading
    2004-06-28 11:57:00  pk2 [View]

    here's the link to the article:
    http://www-106.ibm.com/developerworks/java/library/j-dcl.html
  • Russell Miles photo beware of lazy loading
    2004-07-07 06:45:42  Russell Miles | O'Reilly AuthorO'Reilly Blogger [View]

    Excellent point...

    This article shows off a very simple Lazy Loading strategy. If you are deploying to a multi-threaded environment (and let's face it most production deployments of lazy loading would probably be multi-threaded) then the LazyFeatureProxy class can be made thread safe (and not prone to the problems that Java has with double checked locking) then making the getFeature() method synchronized should do the trick as shown below:



    public synchronized Feature getFeature()
    throws
    IllegalAccessException,
    InstantiationException,
    ClassNotFoundException
    {
    if (this.delegate == null)
    {
    return this.delegate =
    (Feature) Class
    .forName(this.featureClass)
    .newInstance();
    }
    else
    {
    return this.delegate;
    }
    }


    There is a performance penalty for introducing this slight bottle neck ot the system but since the getFeature() call should only be called once in the lifetime of a lazy loaded feature (assuming the features are not unloaded at some point) then this performance penalty should not be too intrusive.

    Cheers for the feedback!