4

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

2
  • 6
    new MyClass() executed once? Commented Jan 14, 2010 at 6: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 (stackoverflow.com/questions/2055016/web-site-design-idea-closed)! At least you should know (master?) the GoF patterns. Commented Jan 14, 2010 at 8:33

4 Answers 4

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.

Sign up to request clarification or add additional context in comments.

5 Comments

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
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, refer to Effective Java. Java enums are much more than the simple enums that are available in other languages.
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: en.wikipedia.org/wiki/Enumeration and en.wikipedia.org/wiki/Enumeration_(programming)
As singleton class, is Enum instantiated only once?
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.

4 Comments

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.
The only improvement I'd make to this is lazy initialization of the singleton.
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.
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 :)
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

7 Comments

Thats why I've added a link. There is no use of repeating the same information here
didn't see the link, your edit and my comment must have been asynchronous .. I've removed the -1
Why do I need to reinvent the wheel and put all information here while having thousands of resources on web?
(I want to point out that I did not downvote that, for once.)
sigh it claims my vote is too old ... strange since I am certain there was no link (that's why I went to look for one). My appologies, the -1 vote is undeserved!
|
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[];   

} 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.