commons-dev mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From Cory Klein <>
Subject [POOL] Improving the borrow/return process with anonymous functions
Date Thu, 12 Nov 2015 17:46:57 GMT
First off, hello! My name is Cory Klein and this marks my first
interaction with this group. I've read through the email guidelines
and I think I have something productive to discuss here.

In looking at GenericObjectPool I came across a process that I believe
could be improved upon and I wanted to get some early feedback on this
approach before investing the time to create a full pull request.

The general approach for using an object pool is to borrow an object,
use it to do something, and then return it. For example:

Resource resource = objectPool.borrowObject();
String result = doSomething(resource);

In this case, objectPool owns instances of Resource and lends them
out. However, the object pool abstraction gets slightly leaky when you
consider that the consumer has a responsibility to return the object,
and other consumers might be adversely affected if objects aren't
returned properly.

I propose augmenting ObjectPool with the following method. This code
is merely demonstrative and not intended to be final:

public class <T> ObjectPool {

    public R run(Function<T,R> function) {
        T obj = null;
        try {
            obj = borrowObject();
        } catch (Exception e) {
            throw new RuntimeException("Unable to get object from pool");
        R returnVal = null;
        try {
            returnVal = function(T);
        } catch (Exception e) {
            throw new RuntimeException("Supplied lambda produced an exception");
        } finally {
            return returnVal;

With this idea, consumers can instead provide the object pool with a
function to run using the required resource, leaving the object pool
complete ownership of the resource and ensuring that resources can
always be returned to the pool. The borrow/return example from above
becomes merely:

String result = -> doSomething(resource));

In summary, some positive reasons I can think of to make this change are:

* Improve a leaky abstraction
* Less code needed on the consuming side
* Improved reliability

I'm having a harder time coming up with reasons why this change is
bad, but I think this may be due to a lack of intimacy with the
library as it exists now. Are there any reasons that are immediately
apparent to you?


Cory Klein

To unsubscribe, e-mail:
For additional commands, e-mail:

View raw message