Menu

#21 Bad singleton patern

open
strutsdoc (3)
5
2005-01-06
2005-01-06
Gabarren
No

Hello,

In XMLUtils.java we found

public static XMLUtils getInstance() {
if (self == null) {
synchronized(XMLUtils.class) {
self = new XMLUtils();
}
}
return self;
}

instead of the right singleton patern (with double check)

public static XMLUtils getInstance() {
if (self == null) {
synchronized(XMLUtils.class) {
if (self == null) {
self = new XMLUtils();
}
}
}
return self;
}

Without this double-check, if a 2nd thread (or more) is
waiting on synchronize during the 1st thread (the
instancier's one), it will instance an other class (on
more).

Have fun and thanks for your good job,
Jef

Discussion

  • Gabarren

    Gabarren - 2005-01-06
    • assigned_to: nheudecker --> nobody
     
  • Nick Heudecker

    Nick Heudecker - 2005-01-06
    • assigned_to: nobody --> nheudecker
     
  • David McReynolds

    Logged In: YES
    user_id=683632

    I wouldn't waste my time with DCL.

    "There's only one problem with it -- it doesn't work. Why
    not? The most obvious reason is that the writes which
    initialize instance and the write to the instance field can
    be reordered by the compiler or the cache, which would have
    the effect of returning what appears to be a partially
    constructed Something. The result would be that we read an
    uninitialized object. There are lots of other reasons why
    this is wrong, and why algorithmic corrections to it are
    wrong. There is no way to fix it using the old Java memory
    model."
    http://www.cs.umd.edu/~pugh/java/memoryModel/DoubleCheckedLocking.html

     

Log in to post a comment.

Want the latest updates on software, tech news, and AI?
Get latest updates about software, tech news, and AI from SourceForge directly in your inbox once a month.