One instance of the Java class

I want to create one instance of a class. How to create one instance of a class in Java?

+3
source share
4 answers

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

public enum MyClass {
  INSTANCE;

  // Methods go here
}

The syntax pattern uses a static state, and as a result usually leads to chaos in unit testing.

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

+17
source

Very simple 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 template.

public class Singleton {

  private Singleton() { 
    // hidden constructor
  }

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

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

, getInstance(), - , JVM/classloader , .

+10

singleton.

:

singleton? singleton - ,

+5
In Java, how can we have one instance of the BrokerPacket class in two threads? 

, , BrokerLocation . :

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[];   

} 
+1

Source: https://habr.com/ru/post/1728417/


All Articles