Codementor Events

Get a low cost Java singleton

Published Sep 15, 2018Last updated Sep 30, 2018
Get a low cost Java singleton

Before starting: this is about a cheap implementation, you can use it for any purpose, the point of the post is show an alternative supported by the language.

Using singletons to write any app in a object oriented language is almost mandatory if you have to control the access to certain resource through a unique object, e.g.: a connection to a database.

There's a few of tools/techniques to achieve this:

  • Using the @Singleton annotation of Java EE6: Link to doc

  • Programming your own singleton pattern implementation: Examples

  • The low cost alternative: Use Enum
    As you probably knows (or not), an enumeration in Java is represented by an special data type Enum. This data type allow to set predefined constants, and this constants are objects instantiated once. So:

public class App {
    public static void main(String args[]) {
        Thing.INSTANCE.sayHi();
    }
   
     public enum Thing {
        INSTANCE;
        
        public void sayHi(){
        	System.out.println("Hi from: " + this.getClass());
        }
    }
}

Output is:

Hi from: class App$Thing

I hope helps in case of you're looking for a very fast way to get a singleton, you must know that there's a few of disadvantages that are very away to be a blocking.

Discover and read more posts from Federico Rossi
get started
post commentsBe the first to share your opinion
Show more replies