Gautam created POOL-218:
---------------------------

             Summary: Does borrowObject block?
                 Key: POOL-218
                 URL: https://issues.apache.org/jira/browse/POOL-218
             Project: Commons Pool
          Issue Type: Bug
    Affects Versions: 1.6
         Environment: Mac lion and java 1.6
            Reporter: Gautam
            Priority: Trivial


I'm trying to pool some objects and share them but I noticed blocking in the 
threads.  I'm a bit new to Java so not sure if this is a problem with my lack 
of experience or something specific to pools. Here's some code that replicates 
the problem(Create 10 threads and share 20 objects, do this in a long loop so 
you can catch the blocking). If you profile it, you'll notice that borrowObject 
seems to be blocking the thread.  So the question is, is this normal behavior 
or am I doing something wrong?

Code:

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import org.apache.commons.pool.BasePoolableObjectFactory;
import org.apache.commons.pool.ObjectPool;
import org.apache.commons.pool.impl.GenericObjectPool;

public class main{
    public static void main(String[] a){
        ObjectPool<Foo> fpool = new GenericObjectPool<Foo>(new 
FooPoolableObjectFactory(), 20);
        ExecutorService tpool = Executors.newFixedThreadPool(10);
        
        for(int i = 0; i < 900000000; ++i){
            tpool.submit(new FooWorker(fpool));
        }
    }
}

class Foo{
    private static int pk = 0;
    private int count = 0;
    public final int id;
    
    public Foo(){
        id = pk++;
    }
    
    public int increment(){
        return ++count;
    }
}

class FooWorker implements Runnable{
    private ObjectPool<Foo> fpool;
    
    public FooWorker(ObjectPool<Foo> fpool){
        this.fpool = fpool;
    }
    
    @Override
    public void run(){
        Foo foo = null;
        try{
            foo = fpool.borrowObject();
            //System.out.println(foo.id + ": " + foo.increment());
        }
        catch(Exception e){
            e.printStackTrace();
        }
        finally{
            // This is done in a finally block to ensure the object is returned 
to the pool
            if(foo != null){
                try{
                    fpool.returnObject(foo);
                }
                catch(Exception e){
                    e.printStackTrace();
                }
            }
        }
    }
}

class FooPoolableObjectFactory extends BasePoolableObjectFactory<Foo>{
    
    @Override
    public Foo makeObject() throws Exception{
        return new Foo();
    }
}

--
This message is automatically generated by JIRA.
If you think it was sent incorrectly, please contact your JIRA administrators: 
https://issues.apache.org/jira/secure/ContactAdministrators!default.jspa
For more information on JIRA, see: http://www.atlassian.com/software/jira

        

Reply via email to