• Post Reply Bookmark Topic Watch Topic
  • New Topic

find number of objects for a particular class and create objects accordingly?  RSS feed

 
Abhishek Reddy
Ranch Hand
Posts: 259
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Prashant R Kataria
Greenhorn
Posts: 20
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In such scenarios one should use resource pool mechanism.
 
Peter Chase
Ranch Hand
Posts: 1970
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Abhishek Reddy
Ranch Hand
Posts: 259
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
thanks for the reply..

is there any other way of solving the problem.
 
Nitesh Kant
Bartender
Posts: 1638
IntelliJ IDE Java MySQL Database
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!