Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I find where an instance of a Java singleton is created?

In a large, complex program it may not be simple to discover where in the code a Singleton has been instantiated. What is the best approach to keep track of created singleton instances in order to re-use them?

Regards, RR

like image 317
recoInrelax Avatar asked Mar 03 '26 18:03

recoInrelax


2 Answers

A Singleton usually has a private constructor, thus the Singleton class is the only class which can instantiate the one and only singleton instance.

like image 86
stacker Avatar answered Mar 05 '26 08:03

stacker


It's the responsibilty of singleton class developer to make sure that the instance is being reused on multiple calls.

As a user, you shouldn't worry about it.

class Singelton
{
    private static Singelton _singelton = null;

    private Singelton()
    {

    }

    // NOT usable for Multithreaded program
    public static Singelton CreateMe()
    {
        if(_singelton == null)
            _singelton = new Singelton();
        return _singelton;        
    }
}

Now, from anywhere in your code, you can instantiate Singelton, how many times you like and each time assign it to different reference. but c'tor is called ONLY once.

like image 41
Azodious Avatar answered Mar 05 '26 08:03

Azodious



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!