Search code examples
javaspringconcurrencypooling

Spring ObjectPooling & thread blocking


I have a Spring CommonsPoolTargetSource defined for a bean. I'm trying to understand how pooling works, and when an object is returned the the pool.

Specifically, if I have a worker, which takes a pooled object and invokes two methods on it, as follows:

public class MyWorker {
    @Resource
    Foo pooledFoo;

    void doWork()
    {
        pooledFoo.doStepA();
        pooledFoo.doStepB();
    }
}

From what I can see in the tests I've run, pooledFoo is not actually an instance of Foo, but a proxy provided by the Pool. The flow in the above would be:

  • Invoking doStepA() on foo retrieves a value from the pool (blocking the thread if one is not available),
  • doStepA is executed on the pooledFoo
  • when doStepA completed, pooledFoo instance is returned to the pool
  • control returns to the doWork method, and the method continues

If this is correct (please tell me if it's not), is it fair to assume that the pooledFoo returned from the pool when doStepB() is invoked, will not be the same instance that was returned for doStepA()?


Solution

  • Your description of the flow is correct - the object will be borrowed from the pool before each invocation, and returned to it afterwards.

    However, you next assumption is wrong - it's entirely possible that stepB will be invoked against the same pooled instance as stepA. It depends on the "churn" on the pool - how often are objects borrowed and returned by different threads. Under low load, the same object might be reused.

    So there's no guarantee of anything here. With pooled objects, you generally want to leave the pooled object in a state where it is fit to be used by the next borrower, regardless of whether not the borrower is the same thread.