Uploaded image for project: 'JDK'
  1. JDK
  2. JDK-4388153

Template code is incorrect!!!

XMLWordPrintable

    • Icon: Bug Bug
    • Resolution: Fixed
    • Icon: P4 P4
    • 1.4.0
    • 1.3.0
    • docs
    • merlin
    • generic
    • generic



      Name: yyT116575 Date: 11/10/2000


      This is a documentation error in question of the week 111

      The solution to Question Of The Week 111 gives an invalid template for
      implementing the singleton pattern. This is particularly problematical as the
      error in the code is insidious. The code suggests this pattern:

      class Singleton {
          private final static theInstance=new Singleton();
          private Singleton(){}
          public static Singleton getInstance() {
              return theInstance;
          }
      }

      But for correct operation this depends upon the instantiation of the singleton
      instance happening as last thing in the textual set of static class initializers
      (this is how the JLS defines the order of class initializers).

      So if an implementation of the code looks like this:

      class Singleton {
          private static Singleton theInstance = new Singleton();
          private static int theInt = 0xdeadbeef;
          private int anotherInt;

          private Singleton() {
              anotherInt = theInt+1;
          }

          public static Singleton getInstance() {
              return(theInstance);
          }

          public int getThatInt() {
              return(anotherInt);
          }
      }

      Then anotherInt will not have the correct value. As you can see, the error is
      extremely insidious. Given the prevalence of usage of the singleton pattern you
      should correct the implementation given in question of the week.
      (Review ID: 112078)
      ======================================================================

            busersunw Btplusnull User (Inactive)
            yyoungsunw Yung-ching Young (Inactive)
            Votes:
            0 Vote for this issue
            Watchers:
            0 Start watching this issue

              Created:
              Updated:
              Resolved:
              Imported:
              Indexed: