3

I'm using Jakarta commons-pool-1.5.6.jar. I have 2 different pool of the same type of object (ex : Car). Is the a way to prevent returning object to the pool?

Here's a sample:

//CarPool extends BaseObjectPool
CarPool carPoolA =  new CarPool(); 
CarPool carPoolB =  new CarPool();
carPoolB.returnObject(carPoolA.borrowObject());

I would have thought the pool would've manage its content and prevent returning an external object to it?

Any thought on this? Do I have to manage this myself?

skaffman
  • 398,947
  • 96
  • 818
  • 769
  • 1
    All pooled objects should contain a private reference to their own pool, loaded in at pool creation time. This makes releasing objects back to the pool parameterless: 'myCar.release();' then automagically returns the object to the correct pool, so preventing objects being released to the wrong pool and reducing the number of pool references that have to be passed around. Descend all your cars, trucks, dealers, garages etc. from a 'pooledObject' class that encapsulates this behaviour. – Martin James May 25 '11 at 18:52

2 Answers2

1

I don't think the default implementation has any thing that do what you described (by looking through their APIs). But you can either configure the GenericObjectPool to achieve your goal, or write the logic into your CarPool. So I guess ultimately my answer to your question is yes, you will have to manage that yourself.

Alvin
  • 10,308
  • 8
  • 37
  • 49
  • Ultimately, this is what I've done. I've wrapped the pool and now control in and out. Remembering object borrowed from my pool and validating that they did indeed come from this pool when returned. – Olivier Quirion Aug 03 '11 at 11:47
0

The answer above is correct for 1.x pools. These pools do not maintain internal references to checked out objects, so they can't test membership on return, or guard against multiple returns of the same object.

Version 2.x pools check to make sure that a returning object was borrowed from the pool it is returning to. Returning an object that was not borrowed from a pool, or returning an object that has already been returned will result in an IllegalStateException in 2.x pools.

Phil Steitz
  • 644
  • 3
  • 10