When we want to create only one object of class, we use singleton design pattern. I want to create maximum 3 or 5 objects of my class. Is there any way to restrict maximum number of object creation in Java?
Of course you could implement a singleton-like feature rather easily, but what you're apparently looking for is an Object Pool.
There are many implementations of such pools, a notable one is apache commons/pool
As seanizer mentioned you would be implementing something that has been done, but, if you just have this one class that you are concerned about, adding a new jar file and using it for such a trivial operation seems like overkill to me.
A simple approach is to have an array of n (3-5), and have a private constructor in your "singleton" class. Then you will have an instanceOf
method, which is the only way to get an object.
This method will look to see if the number of created objects is < n, if it is, it creates a new one and returns it.
But, what do you want to do if all the objects are already given out?
You will need to be certain to have the object returned back to the pool when you are done with it, otherwise you will run out of objects to hand out.
When you hand out an object, you can copy that to a collection, or array, to know that it is already out, or, just have an array of n of boolean that is true when the object is available to be handed out.
The basic design is simple, the complexity is in how to handle the conditions that might be error conditions, in the rest of your program.
Also, you need to ensure that you use a finally
block to return the object back, so that in case of exception the object is still returned.
Have a static field in the class that counts the number of times an instance has been created.
class Foo {
private static Integer num_instances = 0, MAX = 3;
public Foo() throws Exception {
synchronized(Foo.num_instances) {
if(Foo.num_instances > MAX) throw new Exception();
Foo.num_instances++;
}
}
}
EDIT: it's probably bad form to throw an exception from a constructor, so you could do the following instead:
class Foo {
private static Integer num_instances = 0, MAX = 3;
public Foo try_to_get_a_new_foo() {
synchronized(Foo.num_instances) {
if(Foo.num_instances > MAX) return null;
Foo.num_instances++;
return new Foo();
}
}
}
EDIT 2: If you want pooling (max num in memory at any given time), just implement finalize():
class Foo {
private static Integer num_instances = 0, MAX = 3;
public Foo try_to_get_a_new_foo() {
synchronized(Foo.num_instances) {
if(Foo.num_instances > MAX) return null;
Foo.num_instances++;
return new Foo();
}
}
public void finalize() {
synchronized(Foo.num_instances) {
Foo.num_instances--;
}
super.finalize();
}
}
Here's my friend Tripleton, he might be able to help you, his cousin Quinton is rather self-explanatory :).
Edit:
bad code removed, lest someone might actually use it, apparently the joke was quite non-obvious :)