tags:

views:

123

answers:

5

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?

+5  A: 

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

seanizer
+1  A: 

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.

James Black
A: 

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();
  }
}
twolfe18
The problem here is that the objects may have been garbage collected long ago while the count remains. You need to keep those objects in memory to change that, and then you've got a pool again.
seanizer
The attempt at synchronization on Foo.num_instances is completely wrong here, since you're changing the instance on which you're synchronizing inside the synchronized code. It doesn't do wat you think it does.
Jorn
@seanizer OP said "i want to create maxium 3 or 5 objects my class", he didn't mention anything about how many instances were in memory.@Jorn - Foo.num_instances is static, so I'm not changing the instance which I'm synchronizing on. Please provide a code example or a clear explanation before saying I'm "completely wrong".
twolfe18
@twolfe18 yes, I know, but: working as a consultant, if I only did what the clients say and didn't try to read their minds for what they mean, I'd never get any jobs :-)
seanizer
@seanizer yes, I know, you are right in principle. But if I admitted that right away what kind of programmer would I be?
twolfe18
A: 

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 :)

darri
That's a terrible way of doing it.
someguy
So you would have to check all 3 cases to find an open slot, and hope you aren't in race condition with other threads doing the same thing :)
bwawok
Well, this was meant as a joke :)
darri
There are much better ways then this.
amra
+1 for your humour
Maurice Perry
Thank you Maurice, I've learn't you can't be too careful with code-humor on SO :).
darri
A: 

May be you are looking for Multiton Pattern

Emil