Jeus
Jeus

Reputation: 486

How can I know whether an instance of a class already exists in memory?

How can I know whether an instance of a class already exists in memory?


My problem is that don't want read method if exist instance of Class this is my code

private void jButton (java.awt.event.ActionEvent evt) {
    PNLSpcMaster pnlSpc = new PNLSpcMaster();
    jtabbedPanel.addTab("reg",pnlSpc);
}

I want check instance of PNLSpcMaster of course I can check by static boolean but I think this way is better.

Upvotes: 4

Views: 18364

Answers (5)

OscarRyz
OscarRyz

Reputation: 199264

If you want to have only one instance of "PNLSpcMaster" then you do need a singleton:

This is the common singleton idiom:

public class PNLSpcMaster {

   /**
    * This class attribute will be the only "instance" of this class
    * It is private so none can reach it directly. 
    * And is "static" so it does not need "instances" 
    */        
   private static PNLSpcMaster instance;

   /** 
     * Constructor make private, to enforce the non-instantiation of the 
     * class. So an invocation to: new PNLSpcMaster() outside of this class
     * won't be allowed.
     */
   private PNLSpcMaster(){} // avoid instantiation.

   /**
    * This class method returns the "only" instance available for this class
    * If the instance is still null, it gets instantiated. 
    * Being a class method you can call it from anywhere and it will 
    * always return the same instance.
    */
   public static PNLSpcMaster getInstance() {
        if( instance == null ) {
            instance = new PNLSpcMaster();
        }
         return instance;
   }
   ....
 }

Usage:

private void jButton (java.awt.event.ActionEvent evt) {
    // You'll get the "only" instance.        
    PNLSpcMaster pnlSpc = PNLSpcMaster.getInstace(); //<-- getInstance()
    jtabbedPanel.addTab("reg",pnlSpc);
}

Or directly:

private void jButton (java.awt.event.ActionEvent evt) {
    jtabbedPanel.addTab("reg",PNLSpcMaster.getInstace());
}

For basic usages the Singleton Pattern works very well. However for more sophisticated usages it may be dangerous.

You could read more about it: Why singletons are controversial

Upvotes: 8

Vineet Reynolds
Vineet Reynolds

Reputation: 76719

Several factors would contribute to obtaining a reliable solution in Java, as opposed to C++.

The following example is unreliable, although it could provide you with a correct enough answer if you use the hasAtleastOne() method.

class Example {
    private static int noOfInstances = 0;

    public Example() {
        noOfInstances++;
    }


    public static boolean hasAtleastOne() {
        if(noOfInstances > 0)
            return true;
        else
            return false;
    }

    protected void finalize() throws Throwable {
        noOfInstances--;
    }
}

The unreliability stems out of the fact that destructors are not available in Java, unlike C++. It is upto the garbage collector to release the memory consumed by an instance - the instance could still be floating in memory as an orphan since no other object references it. Hence, you never know whether an object is no longer being referenced.

Admittedly, that is theoretically different from being absent in memory at all, but you will have to wait for the finalize() method to be called before you know for sure that no such instance of the class is available. Finalizers come with a warning - they are not to be relied upon in time-critical applications, since it could be a factor of a few seconds to minutes between object orphaning and finalization; in short there is no guarantee that they could be called.

The Dispose Pattern

You could add more reliability to the solution by implementing the Dispose pattern. This also requires the client of the class to invoke the dispose method to signal that the instance is to be disposed off, so that the instance count can be reduced. Poorly written clients will make the solution unreliable.

Upvotes: 1

John Rayner
John Rayner

Reputation: 3535

For classes that have a notion of identity, the Identity Map pattern applies.

Upvotes: 0

Andrew
Andrew

Reputation: 12009

I think you're after the singleton pattern.

Upvotes: 1

Igor ostrovsky
Igor ostrovsky

Reputation: 7392

There isn't a reasonable way to find out whether or not an instance of a particular class already exists.

If you need to know this information, create a static boolean field and set it from the constructor:

class MyClass {
    private static bool instanceExists = false;
    public MyClass() {
        MyClass.instanceExists = true;
    }
}

Upvotes: 0

Related Questions