Arasu
Arasu

Reputation: 2148

How do i check a class is instantiated in JAVA

I'm trying to implement singleton concept in my play application. But before going into singleton concept can we find a class is instantiated, how many times it is instantiated

Upvotes: 0

Views: 5567

Answers (5)

Jarek Przygódzki
Jarek Przygódzki

Reputation: 4412

Thread-safe singletons

Upvotes: 0

frostmatthew
frostmatthew

Reputation: 3298

ake the instantiation protected:

    protected SingleClassName() {
       //your stuff here
    }

And what is publiclay accessible would be:

public static SingleClassNameGetInstance() {
    if (instance == null) {
        instance = new SingleClassName();
    }
    return instance;
}

You'll just need a private variable for it to check, something like:

private static instance = null;

Upvotes: 0

Teja Kantamneni
Teja Kantamneni

Reputation: 17472

The idea of a singleton pattern is to make sure nobody will create an instance except for the Class itself. To do this we will make the constructor private so that nobody can instantiate it from outside. Then we will maintain a private variable which holds the instance of the class and a static method like getInstance which will return the instance. The full sample implementation can be found here. There are numerous implementation examples online too..

Upvotes: 1

Jon Skeet
Jon Skeet

Reputation: 1502106

The simplest way would be to include a thread-safe static counter which is updated in your constructor:

public class CountedClass {
    private static final AtomicInteger counter = new AtomicInteger();

    public CountedClass() {
        counter.incrementAndGet();
    }

    public static int getInstanceCount() {
        return counter.get();
    }
}

Note that this will not show how many instances are currently alive, as it doesn't decrement the counter on destruction. You could override finalize to do that, but I wouldn't.

Also note that this is not the same thing as a singleton by a long chalk. The recommended ways of achieving a singleton are either using a single-value enum:

public enum Singleton
{
    INSTANCE;

    // Methods here
}

or like this:

public final class Singleton {
    // Thread-safe due to guarantees about initializers
    private static final Singleton instance = new Singleton();

    private Singleton() {
    }

    public static Singleton getInstance() {
        return instance;
    }
}

You can use a nested type to achieve lazier initialization if you really need to, but I've rarely found that to be worth the complexity - the above patterns have always done me fine.

Upvotes: 2

NimChimpsky
NimChimpsky

Reputation: 47290

public class Singleton {

   private static Singleton instance = null;

   private Singleton() {
   }

   public static Singleton getInstance() {
      if(instance == null) {
         instance = new Singleton();
      }
      return instance;
   }
}

Upvotes: 0

Related Questions