A "file" isn't a Java object (and java.io.File definitely isn't a singleton). I wouldn't think of files on disk as a singleton either - they're just shared resources. In particular, it's not like there's only one file on disk :)

A more common example of the singleton pattern is configuration - or logging. For example, LogManager.getLogManager returns "the" LogManager, and you can't create new ones. Likewise you might have one common configuration object which can be accessed statically. (In a dependency injected system the configuration may well not be a singleton, however - instead each component is provided the bits of configuration they need so that they don't have to fetch a "common" one.)

Answer from Jon Skeet on Stack Overflow
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ system design โ€บ singleton-design-pattern
Singleton Method Design Pattern - GeeksforGeeks
In Java, a Singleton can be implemented using a static inner class. A class is loaded into memory only once by the JVM. An inner class is loaded only when it is referenced. Therefore, the Singleton instance is created lazily, only when the ...
Published ย  5 days ago
Top answer
1 of 7
4

A "file" isn't a Java object (and java.io.File definitely isn't a singleton). I wouldn't think of files on disk as a singleton either - they're just shared resources. In particular, it's not like there's only one file on disk :)

A more common example of the singleton pattern is configuration - or logging. For example, LogManager.getLogManager returns "the" LogManager, and you can't create new ones. Likewise you might have one common configuration object which can be accessed statically. (In a dependency injected system the configuration may well not be a singleton, however - instead each component is provided the bits of configuration they need so that they don't have to fetch a "common" one.)

2 of 7
1

Yes, but only if all threads access the same file, and you are using a custom implementation (not java.io.File, perhaps a wrapper)

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

Singletons (being often a bad choice) are classes that can have only one instance throughout the whole program.

For example a SingletonConfigFile might look like this. Have in mind that:

  • it is for reading one file only. It would make sense for this to be a config file.
  • if your class can be instantiated more than once, for different files, it is not singleton.
  • don't use this code - it doesn't take into account concurrency problems which are a whole different area of discussion.

.

public SingletonConfigFile {
   private static String filename = "config.xml";
   private File file;
   private static SingletonConfigFile instance;

   private SingletonConfigFile() {
       if (instance != null) {
           throw new Error();
       }
       file = new File(filename);
   }

   public synchronized SingletonConfigFile getInstance() {
      if (instance == null) {
          instance = new SignletonConfigFile();
      }
      return instance
   }

   public String read() {
       // delegate to the underlying java.io.File
   }
}

But this example is on the edge of sense. Singletons are used in cases when there is only one object (as I stated above). For example it would make sense to have:

  • RingOfPower.getInstance() - there is only one ring of power (Sauron's), and there can't exist more.
  • Sun.getInstance() - only one star called "sun".
  • all objects in the withing of your application that logically should exist only once - a registry, an application context, etc.
Discussions

What is an efficient way to implement a singleton pattern in Java? - Stack Overflow
The deserialisation protection ... Java 2nd Ed). 2009-07-15T22:45:59.137Z+00:00 ... -1 this is absolutely not the most simple case, it's contrived and needlessly complex. Look at Jonathan's answer for the actually most simple solution that is sufficient in 99.9% of all cases. 2009-09-30T08:16:20.34Z+00:00 ... This is useful when your singleton needs to inherit from a superclass. You cannot use the enum singleton pattern in this case, ... More on stackoverflow.com
๐ŸŒ stackoverflow.com
Singleton pattern in java..
A singleton pattern is used when you want to ensure that throughout the application, there is at most one instance of an object that is instanciated, and that instance is shared between all the processes that needs it. One example is for services that could consume too much resource if initialized and discarded every time they are needed. At my current place of work, we use the pattern for REST services in the back end part of the application. From wikipedia : In software engineering, the singleton pattern is a software design pattern that restricts the instantiation of a class to one. This is useful when exactly one object is needed to coordinate actions across the system. The term comes from the mathematical concept of a singleton. The linked article shows a class diagram for a singleton and some examples. A vary basic singleton class would be: public class Singleton { // If you couldn't tell from the variable name, this is the single instance of your singleton class private static Singleton singleInstance; // The constructor is private to ensure it cannot be called from another class, and then creating another (unwanted) instance private Singleton(){ super(); } // And this method returns your instance public static Singleton getInstance(){ // If the instance doesn't exist, I create it, otherwise I do nothing. if(singleInstance == null){ singleInstance = new Singleton(); // I can call the constructor here because I'm within the class } // Then I return the instance, whether I just created it, or it was preexisting) return singleInstance; } } This is the bare bones for lazy initialization, and doesn't take care of synchronization (which may or may not be needed) More on reddit.com
๐ŸŒ r/javahelp
19
1
January 3, 2019
Can someone explain when to use Singleton, Scoped and Transient with some real life examples?
Singleton: This creates only one instance of a class during the application's lifecycle. Every time you request this class, you get the same instance. Use it for classes that are expensive to create or maintain a common state throughout the application, like a database connection. Transient: Every time you request a transient class, a new instance is created. This is useful for lightweight, stateless services where each operation requires a clean and independent instance. Scoped: Scoped instances are created once per client request. In a web application, for example, a new instance is created for each HTTP request but is shared across that request. Use it for services that need to maintain state within a request but not beyond it, like shopping cart in an e-commerce site. More on reddit.com
๐ŸŒ r/csharp
87
136
January 28, 2024
What pattern to use instead of Singleton?
Unity has a good blog post about this with examples https://blog.unity.com/games/level-up-your-code-with-game-programming-patterns https://github.com/Unity-Technologies/game-programming-patterns-demo More on reddit.com
๐ŸŒ r/Unity3D
122
91
November 18, 2023
๐ŸŒ
Baeldung
baeldung.com โ€บ home โ€บ java โ€บ core java โ€บ singletons in java
Singletons in Java | Baeldung
October 23, 2025 - As for the EnumSingleton, we can use it like any other Java Enum: EnumSingleton enumSingleton1 = EnumSingleton.INSTANCE.getInstance(); System.out.println(enumSingleton1.getInfo()); //Initial enum info EnumSingleton enumSingleton2 = EnumSingleton.INSTANCE.getInstance(); enumSingleton2.setInfo("New enum info"); System.out.println(enumSingleton1.getInfo()); // New enum info System.out.println(enumSingleton2.getInfo()); // New enum info ยท Singleton is a deceptively simple design pattern, and there are a few common mistakes that a programmer might commit when creating a singleton.
๐ŸŒ
AlgoMaster
blog.algomaster.io โ€บ p โ€บ singleton-design-pattern
Singleton Design Pattern and 7 Ways to Implement it
June 24, 2024 - The Bill Pugh Singleton implementation, ... some other patterns like double-checked locking. In this method, the singleton is declared as an enum rather than a class. Java ensures that only one instance of an enum value is created, even ...
๐ŸŒ
DigitalOcean
digitalocean.com โ€บ community โ€บ tutorials โ€บ java-singleton-design-pattern-best-practices-examples
Java Singleton Pattern: Best Practices & Examples | DigitalOcean
November 5, 2022 - To overcome this situation with Reflection, Joshua Bloch suggests the use of enum to implement the singleton design pattern as Java ensures that any enum value is instantiated only once in a Java program. Since Java Enum values are globally accessible, so is the singleton.
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ java โ€บ singleton-class-java
Singleton Method Design Pattern in Java - GeeksforGeeks
To instantiate a normal class, we use a Java constructor. On the other hand, to instantiate a singleton class, we use the getInstance() method. The other difference is that a normal class vanishes at the end of the lifecycle of the application while the singleton class does not destroy with the completion of an application. There are two forms of singleton design patterns, which are:
Published ย  July 23, 2025
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ java โ€บ java-singleton-design-pattern-practices-examples
Java Singleton Design Pattern Practices with Examples - GeeksforGeeks
January 3, 2025 - Eager initialization: This is the simplest method of creating a singleton class. In this, object of class is created when it is loaded to the memory by JVM. It is done by assigning the reference of an instance directly. It can be used when program will always use instance of this class, or the cost of creating the instance is not too large in terms of resources and time. ... // Java code to create singleton class by // Eager Initialization public class GFG { // public instance initialized when loading the class private static final GFG instance = new GFG(); private GFG() { // private constructor } public static GFG getInstance(){ return instance; } }
Find elsewhere
๐ŸŒ
TutorialsPoint
tutorialspoint.com โ€บ design_pattern โ€บ singleton_pattern.htm
Design Patterns - Singleton Pattern
package com.tutorialspoint; public class SingletonPatternDemo { public static void main(String[] args) { //illegal construct //Compile Time Error: The constructor SingleObject() is not visible //SingleObject object = new SingleObject(); //Get the only object available SingleObject object = SingleObject.getInstance(); //show the message object.showMessage(); } } class SingleObject { //create an object of SingleObject private static SingleObject instance = new SingleObject(); //make the constructor private so that this class cannot be //instantiated private SingleObject(){} //Get the only object available public static SingleObject getInstance(){ return instance; } public void showMessage(){ System.out.println("Hello World!"); } }
๐ŸŒ
DEV Community
dev.to โ€บ adityapratapbh1 โ€บ the-singleton-design-pattern-ensuring-a-single-instance-in-java-5c1o
The Singleton Design Pattern: Ensuring a Single Instance in Java - DEV Community
October 24, 2023 - The Singleton Design Pattern assures that a class has only one instance and gives a global point of access to that instance. It is extensively used to manage shared resources and centralise control inside an application in Java and other ...
๐ŸŒ
HowToDoInJava
howtodoinjava.com โ€บ home โ€บ design patterns โ€บ creational โ€บ singleton
Singleton Pattern (with Example)
November 5, 2024 - Singleton pattern enables an application to create the one and only one instance of a Java class per JVM, in all possible scenarios.
๐ŸŒ
Wikipedia
en.wikipedia.org โ€บ wiki โ€บ Singleton_pattern
Singleton pattern - Wikipedia
4 days ago - The following Java 5+ example is a thread-safe implementation, using lazy initialization with double-checked locking. public class Singleton { private static volatile Singleton instance = null; private Singleton() {} public static Singleton getInstance() { if (instance == null) { synchronized (Singleton.class) { if (instance == null) { instance = new Singleton(); } } } return instance; } } Some consider the singleton to be an anti-pattern that introduces global state into an application, often unnecessarily.
Top answer
1 of 16
823

Use an enum:

Copypublic enum Foo {
    INSTANCE;
}

Joshua Bloch explained this approach in his Effective Java Reloaded talk at Google I/O 2008: link to video. Also see slides 30-32 of his presentation (effective_java_reloaded.pdf):

The Right Way to Implement a Serializable Singleton

Copypublic enum Elvis {
    INSTANCE;
    private final String[] favoriteSongs =
        { "Hound Dog", "Heartbreak Hotel" };
    public void printFavorites() {
        System.out.println(Arrays.toString(favoriteSongs));
    }
}

Edit: An online portion of "Effective Java" says:

"This approach is functionally equivalent to the public field approach, except that it is more concise, provides the serialization machinery for free, and provides an ironclad guarantee against multiple instantiation, even in the face of sophisticated serialization or reflection attacks. While this approach has yet to be widely adopted, a single-element enum type is the best way to implement a singleton."

2 of 16
243

Depending on the usage, there are several "correct" answers.

Since Java 5, the best way to do it is to use an enum:

Copypublic enum Foo {
   INSTANCE;
}

Pre Java 5, the most simple case is:

Copypublic final class Foo {

    private static final Foo INSTANCE = new Foo();

    private Foo() {
        if (INSTANCE != null) {
            throw new IllegalStateException("Already instantiated");
        }
    }

    public static Foo getInstance() {
        return INSTANCE;
    }

    public Object clone() throws CloneNotSupportedException{
        throw new CloneNotSupportedException("Cannot clone instance of this class");
    }
}

Let's go over the code. First, you want the class to be final. In this case, I've used the final keyword to let the users know it is final. Then you need to make the constructor private to prevent users to create their own Foo. Throwing an exception from the constructor prevents users to use reflection to create a second Foo. Then you create a private static final Foo field to hold the only instance, and a public static Foo getInstance() method to return it. The Java specification makes sure that the constructor is only called when the class is first used.

When you have a very large object or heavy construction code and also have other accessible static methods or fields that might be used before an instance is needed, then and only then you need to use lazy initialization.

You can use a private static class to load the instance. The code would then look like:

Copypublic final class Foo {

    private static class FooLoader {
        private static final Foo INSTANCE = new Foo();
    }

    private Foo() {
        if (FooLoader.INSTANCE != null) {
            throw new IllegalStateException("Already instantiated");
        }
    }

    public static Foo getInstance() {
        return FooLoader.INSTANCE;
    }
}

Since the line private static final Foo INSTANCE = new Foo(); is only executed when the class FooLoader is actually used, this takes care of the lazy instantiation, and is it guaranteed to be thread safe.

When you also want to be able to serialize your object you need to make sure that deserialization won't create a copy.

Copypublic final class Foo implements Serializable {

    private static final long serialVersionUID = 1L;

    private static class FooLoader {
        private static final Foo INSTANCE = new Foo();
    }

    private Foo() {
        if (FooLoader.INSTANCE != null) {
            throw new IllegalStateException("Already instantiated");
        }
    }

    public static Foo getInstance() {
        return FooLoader.INSTANCE;
    }

    @SuppressWarnings("unused")
    private Foo readResolve() {
        return FooLoader.INSTANCE;
    }
}

The method readResolve() will make sure the only instance will be returned, even when the object was serialized in a previous run of your program.

๐ŸŒ
Refactoring.Guru
refactoring.guru โ€บ home โ€บ design patterns โ€บ singleton โ€บ java
Singleton in Java / Design Patterns
January 1, 2026 - Full code example in Java with detailed comments and explanation. Singleton is a creational design pattern, which ensures that only one object of its kind exists and provides a single point of access to it for any other code.
๐ŸŒ
Reddit
reddit.com โ€บ r/javahelp โ€บ singleton pattern in java..
r/javahelp on Reddit: Singleton pattern in java..
January 3, 2019 -

What is singleton pattern in java..? what advantage of use this.? why singleton pattern is used??. please explain me with real life example..

Top answer
1 of 2
3
A singleton pattern is used when you want to ensure that throughout the application, there is at most one instance of an object that is instanciated, and that instance is shared between all the processes that needs it. One example is for services that could consume too much resource if initialized and discarded every time they are needed. At my current place of work, we use the pattern for REST services in the back end part of the application. From wikipedia : In software engineering, the singleton pattern is a software design pattern that restricts the instantiation of a class to one. This is useful when exactly one object is needed to coordinate actions across the system. The term comes from the mathematical concept of a singleton. The linked article shows a class diagram for a singleton and some examples. A vary basic singleton class would be: public class Singleton { // If you couldn't tell from the variable name, this is the single instance of your singleton class private static Singleton singleInstance; // The constructor is private to ensure it cannot be called from another class, and then creating another (unwanted) instance private Singleton(){ super(); } // And this method returns your instance public static Singleton getInstance(){ // If the instance doesn't exist, I create it, otherwise I do nothing. if(singleInstance == null){ singleInstance = new Singleton(); // I can call the constructor here because I'm within the class } // Then I return the instance, whether I just created it, or it was preexisting) return singleInstance; } } This is the bare bones for lazy initialization, and doesn't take care of synchronization (which may or may not be needed)
2 of 2
-2
When you're thinking about using a singleton, consider whether using static variables and methods would make more sense. Many people don't like the singleton pattern because it's used too often. Consider something like this instead: public class NotASingleton { private static String myProperty; static { //load myProperty from file, for example. myProperty = .... } public static String getMyProperty(){ return myProperty; } } Now you can use that more easily than a singleton. System.out.println(NotASingleton.getMyProperty()); Instead of like this for the singleton: System.out.println(MySingleton.getInstance().getMyProperty()); It might make sense to use a singleton when initializing your class is very expensive, you may not need to initialize it to begin with, and at most you'll only need one instance. If you will always need one instance you may as well just initialize static variables and use static methods.
๐ŸŒ
Tutorialspoint
tutorialspoint.com โ€บ java โ€บ java_singleton_class.htm
Java - Singleton Class
This pattern involves a single class which is responsible to create an object while making sure that only single object gets created. This class provides a way to access its only object which can be accessed directly without need to instantiate ...
๐ŸŒ
Vogella
vogella.com โ€บ tutorials โ€บ DesignPatternSingleton โ€บ article.html
Design Patterns in Java - Singleton - Tutorial
February 25, 2026 - In Java, the Singleton pattern ensures that only one instance of a class is created and provides a global point of access to this instance.
๐ŸŒ
Programiz
programiz.com โ€บ java-programming โ€บ singleton
Example: Java Singleton Class Syntax
In Java, Singleton is a design pattern that ensures that a class can only have one object.
๐ŸŒ
BlueVPS
bluevps.com โ€บ blog โ€บ complete guide to java singleton design pattern
Complete Guide to Java Singleton Design Pattern - Blog BlueVPS
This creational pattern addresses a specific but common requirement in application development - ensuring that only one instance of a particular class exists throughout the entire application lifecycle while providing global access to that instance.
๐ŸŒ
DEV Community
dev.to โ€บ zeeshanali0704 โ€บ mastering-the-singleton-design-pattern-in-java-a-complete-guide-13nn
Mastering the Singleton Design Pattern in Java โ€“ A Complete Guide - DEV Community
August 21, 2025 - The Singleton Pattern is a creational design pattern that ensures a class is instantiated only once during the application's lifecycle and provides global access to that instance.
๐ŸŒ
DZone
dzone.com โ€บ coding โ€บ java โ€บ singleton: 6 ways to write and use in java programming
Singleton: 6 Ways To Write and Use in Java Programming
April 9, 2024 - This is heavily used in enterprise development where many modules each require their own context with many layers. Each context and each layer are good candidates for singleton patterns.