4

I wanna create a single instance of a class. How can I create a single instance of a class in Java?

BuZZ-dEE
  • 6,075
  • 12
  • 66
  • 96
giri
  • 26,773
  • 63
  • 143
  • 176
  • 6
    `new MyClass()` executed once? – Tom Hawtin - tackline Jan 14 '10 at 06:21
  • 2
    OT - quote from earlier question: "I am very familier with java programming language" - girinie, honestly, I didn't expect that question - you *have to* improve your Java skills before you attack your web shop project (http://stackoverflow.com/questions/2055016/web-site-design-idea-closed)! At least you should know (master?) the GoF patterns. – Andreas Dolk Jan 14 '10 at 08:33

4 Answers4

19

To create a truly single instance of your class (implying a singleton at the JVM level), you should make your class a Java enum.

public enum MyClass {
  INSTANCE;

  // Methods go here
}

The singleton pattern uses static state and as a result usually results in havoc when unit testing.

This is explained in Item 3 of Joshua Bloch's Effective Java.

gpampara
  • 11,989
  • 3
  • 27
  • 26
  • To be exact the singleton will be only at classloader level, you have to control all the classloaders in a JVM to be able to guarantee singleton at JVM level – pgras Jan 14 '10 at 09:29
  • I think you will find this is an abuse of what a enum is intended to do. An enum is for multiple related items (e.g. days of the week) so that you can have a type safe way of performing switches/comparisons etc. They are not for a single instance of a class. Singletons get complicated with different classloader structures but this is the case regardless of how you implement it. – Shane Feb 01 '10 at 22:18
  • @Shane, refer to Effective Java. Java enums are much more than the simple enums that are available in other languages. – gpampara Feb 02 '10 at 05:36
  • 1
    If you have a look at definition of an enumeration you will see it is a set of elements. A singleton by definition is a single element. I am fully aware that Java enums are more than C enums as I use them on a regular basis. I just think this is an abuse of the concept. Here are some Wikipedia links: http://en.wikipedia.org/wiki/Enumeration and http://en.wikipedia.org/wiki/Enumeration_(programming) – Shane Feb 03 '10 at 00:42
  • As singleton class, is Enum instantiated only once? – Arun Raaj Jul 05 '18 at 22:13
10

Very basic singleton.

public class Singleton {
  private static Singleton instance;

  static {
    instance = new Singleton();
  }

  private Singleton() { 
    // hidden constructor
  }    

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

You can also use the lazy holder pattern as well

public class Singleton {

  private Singleton() { 
    // hidden constructor
  }

  private static class Holder {
    static final Singleton INSTANCE = new Singleton();
  }

  public static Singleton getInstance() {
    return Holder.INSTANCE;
  }
}

This version will not create an instance of the singleton until you access getInstance(), but due to the way the JVM/classloader handles the creation on the inner class you are guaranteed to only have the constructor called once.

Shane
  • 1,255
  • 14
  • 14
  • 1
    Explanation: I don think there is no way to restrict the execution of Constructor. The solution is to: make the constructor private - so that nobody can invoke it from outside. Use a static function to initialize the only instance of object - if it is NULL, then call the constructor internally. – effkay Jan 14 '10 at 06:34
  • The only improvement I'd make to this is lazy initialization of the singleton. – Taylor Leese Jan 14 '10 at 06:48
  • 1
    Why the static block? You can just init the instance on the same line where you declare it. @Taylor L You don't necessarily always want lazy init, that depends on the rest of the application and its bootstrapping requirements. – Adriaan Koster Jan 14 '10 at 09:15
  • I have heard that inline instantiation can cause issues with older JVM's. You can also use a wrapping class for the instance. This could have also been lazily instantiated but like most things in Java, there are too many ways to skin the proverbial cat to list them all in a simple example :) – Shane Jan 14 '10 at 10:45
5

use the singleton pattern.

Singleton pattern

Update :

What is the singleton pattern? The singleton pattern is a design pattern that is used to restrict instantiation of a class to one object

Chathuranga Chandrasekara
  • 20,548
  • 30
  • 97
  • 138
1
In Java, how can we have one instance of the BrokerPacket class in two threads? 

So that all the threads update store the different BrokerLocation in one location array. For example:

class BrokerLocation implements Serializable {
    public String  broker_host;
    public Integer broker_port;

    /* constructor */
    public BrokerLocation(String host, Integer port) {
        this.broker_host = host;
        this.broker_port = port;
    }
}


public class BrokerPacket implements Serializable {
    public static BrokerLocation locations[];   

}