I want to allow the user to create only some x objects for a class. If the number of objects for that class exceeds need to display some message.
I have done this by keeping the public static method getInstance()and made the constructor as private. getInstance() method will return the object if and only if the number of objects limit is not exceeded. I have used one static variable count which will be incremented each time the method is invoked and based on the count object is returned. Here i have done the mistake, eventhough the count exceeds, i have to check whether the returned objects are still in use or not, i mean they have been garbage collected or not and accordingly i have to return the object.
Can any one tell me is it possible to check whether the objects of the class are garbage collected or not, if collected i have to return objects.
You can't find out whether objects have actually been garbage-collected. But you can find out when objects become available for garbage collection. From the programmer's point of view, the distinction is almost always irrelevant.
Look up the java.lang.ref.WeakReference class. Maybe also PhantomReference.
Betty Rubble? Well, I would go with Betty... but I'd be thinking of Wilma.
Abhishek: is there any other way of solving the problem.
You are trying to keep an account of the number of instances created and being used of a particular class. So, you have to do what Peter has told i.e. have a WeakReference and associate a ReferenceQueue with the reference. So that when this object is eligible for garbage collection i.e. it is no more referenced from anywhere, you can decrease the reference count.
Alternatively, you can assume a well behaved user and provide a method done() in your class that is called by the user of the instance when it is done with the use of the instance. So, getInstance() marks the start of the use of an instance and done() marks the end of use or return to the pool.