4

Can I let a static field of a class keep a reference to an instance of itself? If so, will it keep alive in the jvm without anyone else keeping a reference?

public class StatTest {
    private static StatTest statTest;

    public static StatTest getStatTest () {
        if (statTest== null) {
            statTest= new StatTest ();
            statTest.init();
        }
        return statTest;
    }

    private StatTest() { }
}
2
  • 1
    This is one way to implement the singleton pattern. Just note that this is not thread-safe (ie, things might get broken if you call StatTest.getStatTest() from more than one thread). To compare different singleton implementations (including some thread-safe ones), check stackoverflow.com/questions/7121213/singleton-instantiation/…, an answer I wrote some time ago. Commented Nov 9, 2011 at 9:21
  • Thank you for all the answers! I realize now that this is a really well known pattern. I recognize the name singleton from before, but I've never read about it. Now it will be easy to find information on how to proceed. Thanks alot! Commented Nov 9, 2011 at 9:38

4 Answers 4

7

Yes, This is the concept of the Singleton design pattern!

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

Comments

2

This is one way to create a singleton of a class.

So to answer your question:

  • Yes, it is possible
  • All references to the getStatTest() method will return that instance.

When using this method for a singleton, the method is mostly called getInstance() =)

Comments

1

will it keep alive in the jvm without anyone else keeping a reference?

Yes, as long as the class itself is not eligible for garbage collection (which can only happen if you use a custom classloader).

Comments

0

Congrats. You've reinvented the singleton. http://en.wikipedia.org/wiki/Singleton_pattern

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.