然而,还是有些对象,它们的创建开销是非常大的,比如线程,数据库连接等这些非轻量级的对象。在任何一个应用程序里面,我们肯定会用到不止一个这样的对象。如果有一种很方便的创建管理这些对象的池,使得这些对象能够动态的重用,而客户端代码也不用关心它们的生命周期,还是会很给力的。
在真正开始写代码前,我们先来梳理下一个对象池需要完成哪些功能。
如果有可用的对象,对象池应当能返回给客户端。
客户端把对象放回池里后,可以对这些对象进行重用。
对象池能够创建新的对象来满足客户端不断增长的需求。
需要有一个正确关闭池的机制来确保关闭后不会发生内存泄露。
不用说了,上面几点就是我们要暴露给客户端的连接池的接口的基本功能。
我们的声明的接口如下:
package com.test.pool; /** * represents a cached pool of objects. * * @author swaranga * * @param <t> the type of object to pool. */ public interface pool<t> { /** * returns an instance from the pool. * the call may be a blocking one or a non-blocking one * and that is determined by the internal implementation. * * if the call is a blocking call, * the call returns immediately with a valid object * if available, else the thread is made to wait * until an object becomes available. * in case of a blocking call, * it is advised that clients react * to {@link interruptedexception} which might be thrown * when the thread waits for an object to become available. * * if the call is a non-blocking one, * the call returns immediately irrespective of * whether an object is available or not. * if any object is available the call returns it * else the call returns < code >null< /code >. * * the validity of the objects are determined using the * {@link validator} interface, such that * an object < code >o< /code > is valid if * < code > validator.isvalid(o) == true < /code >. * * @return t one of the pooled objects. */ t get(); /** * releases the object and puts it back to the pool. * * the mechanism of putting the object back to the pool is * generally asynchronous, * however future implementations might differ. * * @param t the object to return to the pool */ void release(t t); /** * shuts down the pool. in essence this call will not * accept any more requests * and will release all resources. * releasing resources are done * via the < code >invalidate()< /code > * method of the {@link validator} interface. */ void shutdown(); }
为了能够支持任意对象,上面这个接口故意设计得很简单通用。它提供了从池里获取/返回对象的方法,还有一个关闭池的机制,以便释放对象。
现在我们来实现一下这个接口。开始动手之前,值得一提的是,一个理想的release方法应该先尝试检查下这个客户端返回的对象是否还能重复使用。如果是的话再把它扔回池里,如果不是,就舍弃掉这个对象。我们希望这个pool接口的所有实现都能遵循这个规则。在开始具体的实现类前,我们先创建一个抽象类,以便限制后续的实现能遵循这点。我们实现的抽象类就叫做abstractpool,它的定义如下:
package com.test.pool; /** * represents an abstract pool, that defines the procedure * of returning an object to the pool. * * @author swaranga * * @param <t> the type of pooled objects. */ abstract class abstractpool <t> implements pool <t> { /** * returns the object to the pool. * the method first validates the object if it is * re-usable and then puts returns it to the pool. * * if the object validation fails, * some implementations * will try to create a new one * and put it into the pool; however * this behaviour is subject to change * from implementation to implementation * */ @override public final void release(t t) { if(isvalid(t)) { returntopool(t); } else { handleinvalidreturn(t); } } protected abstract void handleinvalidreturn(t t); protected abstract void returntopool(t t); protected abstract boolean isvalid(t t); }
在上面这个类里,我们让对象池必须得先验证对象后才能把它放回到池里。具体的实现可以自由选择如何实现这三种方法,以便定制自己的行为。它们根据自己的逻辑来决定如何判断一个对象有效,无效的话应该怎么处理(handleinvalidreturn方法),怎么把一个有效的对象放回到池里(returntopool方法)。
有了上面这几个类,我们就可以着手开始具体的实现了。不过还有个问题,由于上面这些类是设计成能支持通用的对象池的,因此具体的实现不知道该如何验证对象的有效性(因为对象都是泛型的)。因此我们还需要些别的东西来帮助我们完成这个。
我们需要一个通用的方法来完成对象的校验,而具体的实现不必关心对象是何种类型。因此我们引入了一个新的接口,validator,它定义了验证对象的方法。这个接口的定义如下:
package com.test.pool; /** * represents the functionality to * validate an object of the pool * and to subsequently perform cleanup activities. * * @author swaranga * * @param < t > the type of objects to validate and cleanup. */ public static interface validator < t > { /** * checks whether the object is valid. * * @param t the object to check. * * @return <code>true</code> * if the object is valid else <code>false</code>. */ public boolean isvalid(t t); /** * performs any cleanup activities * before discarding the object. * for example before discarding * database connection objects, * the pool will want to close the connections. * this is done via the * <code>invalidate()</code> method. * * @param t the object to cleanup */ public void invalidate(t t); }
上面这个接口定义了一个检验对象的方法,以及一个把对象置为无效的方法。当准备废弃一个对象并清理内存的时候,invalidate方法就派上用场了。值得注意的是这个接口本身没有任何意义,只有当它在对象池里使用的时候才有意义,所以我们把这个接口定义到pool接口里面。这和java集合库里的map和map.entry是一样的。所以我们的pool接口就成了这样:
package com.test.pool; /** * represents a cached pool of objects. * * @author swaranga * * @param < t > the type of object to pool. */ public interface pool< t > { /** * returns an instance from the pool. * the call may be a blocking one or a non-blocking one * and that is determined by the internal implementation. * * if the call is a blocking call, * the call returns immediately with a valid object * if available, else the thread is made to wait * until an object becomes available. * in case of a blocking call, * it is advised that clients react * to {@link interruptedexception} which might be thrown * when the thread waits for an object to become available. * * if the call is a non-blocking one, * the call returns immediately irrespective of * whether an object is available or not. * if any object is available the call returns it * else the call returns < code >null< /code >. * * the validity of the objects are determined using the * {@link validator} interface, such that * an object < code >o< /code > is valid if * < code > validator.isvalid(o) == true < /code >. * * @return t one of the pooled objects. */ t get(); /** * releases the object and puts it back to the pool. * * the mechanism of putting the object back to the pool is * generally asynchronous, * however future implementations might differ. * * @param t the object to return to the pool */ void release(t t); /** * shuts down the pool. in essence this call will not * accept any more requests * and will release all resources. * releasing resources are done * via the < code >invalidate()< /code > * method of the {@link validator} interface. */ void shutdown(); /** * represents the functionality to * validate an object of the pool * and to subsequently perform cleanup activities. * * @author swaranga * * @param < t > the type of objects to validate and cleanup. */ public static interface validator < t > { /** * checks whether the object is valid. * * @param t the object to check. * * @return <code>true</code> * if the object is valid else <code>false</code>. */ public boolean isvalid(t t); /** * performs any cleanup activities * before discarding the object. * for example before discarding * database connection objects, * the pool will want to close the connections. * this is done via the * <code>invalidate()</code> method. * * @param t the object to cleanup */ public void invalidate(t t); } }
准备工作已经差不多了,在最后开始前我们还需要一个终极武器,这才是这个对象池的杀手锏。就是“能够创建新的对象”。我们的对象池是泛型的,因此它们得知道如何去生成新的对象来填充这个池子。这个功能不能依赖于对象池本身,必须要有一个通用的方式来创建新的对象。通过一个objectfactory的接口就能完成这个,它只有一个“如何创建新的对象”的方法。我们的objectfactory接口如下:
package com.test.pool; /** * represents the mechanism to create * new objects to be used in an object pool. * * @author swaranga * * @param < t > the type of object to create. */ public interface objectfactory < t > { /** * returns a new instance of an object of type t. * * @return t an new instance of the object of type t */ public abstract t createnew(); }
我们的工具类都已经搞定了,现在可以开始真正实现我们的pool接口了。因为我们希望这个池能在并发程序里面使用,所以我们会创建一个阻塞的对象池,当没有对象可用的时候,让客户端先阻塞住。我们的阻塞机制是让客户端一直阻塞直到有对象可用为止。这样的话导致我们还需要再增加一个只阻塞一定时间的方法,如果在超时时间到来前有对象可用则返回,如果超时了就返回null而不是一直等待下去。这样的实现有点类似java并发库里的linkedblockingqueue,因此真正实现前我们再暴露一个接口,blockingpool,类似于java并发库里的blockingqueue接口。
这里是blockingqueue的声明:
package com.test.pool; import java.util.concurrent.timeunit; /** * represents a pool of objects that makes the * requesting threads wait if no object is available. * * @author swaranga * * @param < t > the type of objects to pool. */ public interface blockingpool < t > extends pool < t > { /** * returns an instance of type t from the pool. * * the call is a blocking call, * and client threads are made to wait * indefinitely until an object is available. * the call implements a fairness algorithm * that ensures that a fcfs service is implemented. * * clients are advised to react to interruptedexception. * if the thread is interrupted while waiting * for an object to become available, * the current implementations * sets the interrupted state of the thread * to <code>true</code> and returns null. * however this is subject to change * from implementation to implementation. * * @return t an instance of the object * of type t from the pool. */ t get(); /** * returns an instance of type t from the pool, * waiting up to the * specified wait time if necessary * for an object to become available.. * * the call is a blocking call, * and client threads are made to wait * for time until an object is available * or until the timeout occurs. * the call implements a fairness algorithm * that ensures that a fcfs service is implemented. * * clients are advised to react to interruptedexception. * if the thread is interrupted while waiting * for an object to become available, * the current implementations * set the interrupted state of the thread * to <code>true</code> and returns null. * however this is subject to change * from implementation to implementation. * * * @param time amount of time to wait before giving up, * in units of <tt>unit</tt> * @param unit a <tt>timeunit</tt> determining * how to interpret the * <tt>timeout</tt> parameter * * @return t an instance of the object * of type t from the pool. * * @throws interruptedexception * if interrupted while waiting */ t get(long time, timeunit unit) throws interruptedexception; }
boundedblockingpool的实现如下:
package com.test.pool; import java.util.concurrent.blockingqueue; import java.util.concurrent.callable; import java.util.concurrent.executorservice; import java.util.concurrent.executors; import java.util.concurrent.linkedblockingqueue; import java.util.concurrent.timeunit; public final class boundedblockingpool extends <abstractpool> implements <blockingpool> { private int size; private blockingqueue objects; private validator validator; private objectfactory objectfactory; private executorservice executor = executors.newcachedthreadpool(); private volatile boolean shutdowncalled; public boundedblockingpool( int size, validator validator, objectfactory objectfactory) { super(); this.objectfactory = objectfactory; this.size = size; this.validator = validator; objects = new linkedblockingqueue (size); initializeobjects(); shutdowncalled = false; } public t get(long timeout, timeunit unit) { if(!shutdowncalled) { t t = null; try { t = objects.poll(timeout, unit); return t; } catch(interruptedexception ie) { thread.currentthread().interrupt(); } return t; } throw new illegalstateexception( 'object pool is already shutdown'); } public t get() { if(!shutdowncalled) { t t = null; try { t = objects.take(); } catch(interruptedexception ie) { thread.currentthread().interrupt(); } return t; } throw new illegalstateexception( 'object pool is already shutdown'); } public void shutdown() { shutdowncalled = true; executor.shutdownnow(); clearresources(); } private void clearresources() { for(t t : objects) { validator.invalidate(t); } } @override protected void returntopool(t t) { if(validator.isvalid(t)) { executor.submit(new objectreturner(objects, t)); } } @override protected void handleinvalidreturn(t t) { } @override protected boolean isvalid(t t) { return validator.isvalid(t); } private void initializeobjects() { for(int i = 0; i < size; i++) { objects.add(objectfactory.createnew()); } } private class objectreturner implements <callable> { private blockingqueue queue; private e e; public objectreturner(blockingqueue queue, e e) { this.queue = queue; this.e = e; } public void call() { while(true) { try { queue.put(e); break; } catch(interruptedexception ie) { thread.currentthread().interrupt(); } } return null; } } }
上面是一个非常基本的对象池,它内部是基于一个linkedblockingqueue来实现的。这里唯一比较有意思的方法就是returntopool。因为内部的存储是一个linkedblockingqueue实现的,如果我们直接把返回的对象扔进去的话,如果队列已满可能会阻塞住客户端。不过我们不希望客户端因为把对象放回池里这么个普通的方法就阻塞住了。所以我们把最终将对象插入到队列里的任务作为一个异步的的任务提交给一个executor来执行,以便让客户端线程能立即返回。
现在我们将在自己的代码中使用上面这个对象池,用它来缓存数据库连接。我们需要一个校验器来验证数据库连接是否有效。
下面是这个jdbcconnectionvalidator:
package com.test; import java.sql.connection; import java.sql.sqlexception; import com.test.pool.pool.validator; public final class jdbcconnectionvalidator implements validator < connection > { public boolean isvalid(connection con) { if(con == null) { return false; } try { return !con.isclosed(); } catch(sqlexception se) { return false; } } public void invalidate(connection con) { try { con.close(); } catch(sqlexception se) { } } }
还有一个jdbcobjectfactory,它将用来生成新的数据库连接对象:
package com.test; import java.sql.connection; import java.sql.drivermanager; import java.sql.sqlexception; import com.test.pool.objectfactory; public class jdbcconnectionfactory implements objectfactory < connection > { private string connectionurl; private string username; private string password; public jdbcconnectionfactory( string driver, string connectionurl, string username, string password) { super(); try { class.forname(driver); } catch(classnotfoundexception ce) { throw new illegalargumentexception('unable to find driver in classpath', ce); } this.connectionurl = connectionurl; this.username = username; this.password = password; } public connection createnew() { try { return drivermanager.getconnection( connectionurl, username, password); } catch(sqlexception se) { throw new illegalargumentexception('unable to create new connection', se); } } }
现在我们用上述的validator和objectfactory来创建一个jdbc的连接池:
package com.test; import java.sql.connection; import com.test.pool.pool; import com.test.pool.poolfactory; public class main { public static void main(string[] args) { pool < connection > pool = new boundedblockingpool < connection > ( 10, new jdbcconnectionvalidator(), new jdbcconnectionfactory('', '', '', '') ); //do whatever you like } }
为了犒劳下能读完整篇文章的读者,我这再提供另一个非阻塞的对象池的实现,这个实现和前面的唯一不同就是即使对象不可用,它也不会让客户端阻塞,而是直接返回null。具体的实现在这:
package com.test.pool; import java.util.linkedlist; import java.util.queue; import java.util.concurrent.semaphore; public class boundedpool < t > extends abstractpool < t > { private int size; private queue < t > objects; private validator < t > validator; private objectfactory < t > objectfactory; private semaphore permits; private volatile boolean shutdowncalled; public boundedpool( int size, validator < t > validator, objectfactory < t > objectfactory) { super(); this.objectfactory = objectfactory; this.size = size; this.validator = validator; objects = new linkedlist < t >(); initializeobjects(); shutdowncalled = false; } @override public t get() { t t = null; if(!shutdowncalled) { if(permits.tryacquire()) { t = objects.poll(); } } else { throw new illegalstateexception('object pool already shutdown'); } return t; } @override public void shutdown() { shutdowncalled = true; clearresources(); } private void clearresources() { for(t t : objects) { validator.invalidate(t); } } @override protected void returntopool(t t) { boolean added = objects.add(t); if(added) { permits.release(); } } @override protected void handleinvalidreturn(t t) { } @override protected boolean isvalid(t t) { return validator.isvalid(t); } private void initializeobjects() { for(int i = 0; i < size; i++) { objects.add(objectfactory.createnew()); } } }
考虑到我们现在已经有两种实现,非常威武了,得让用户通过工厂用具体的名称来创建不同的对象池了。工厂来了:
package com.test.pool; import com.test.pool.pool.validator; /** * factory and utility methods for * {@link pool} and {@link blockingpool} classes * defined in this package. * this class supports the following kinds of methods: * * <ul> * <li> method that creates and returns a default non-blocking * implementation of the {@link pool} interface. * </li> * * <li> method that creates and returns a * default implementation of * the {@link blockingpool} interface. * </li> * </ul> * * @author swaranga */ public final class poolfactory { private poolfactory() { } /** * creates a and returns a new object pool, * that is an implementation of the {@link blockingpool}, * whose size is limited by * the <tt> size </tt> parameter. * * @param size the number of objects in the pool. * @param factory the factory to create new objects. * @param validator the validator to * validate the re-usability of returned objects. * * @return a blocking object pool * bounded by <tt> size </tt> */ public static < t > pool < t > newboundedblockingpool( int size, objectfactory < t > factory, validator < t > validator) { return new boundedblockingpool < t > ( size, validator, factory); } /* * creates a and returns a new object pool, * that is an implementation of the {@link pool} * whose size is limited * by the <tt> size </tt> parameter. * * @param size the number of objects in the pool. * @param factory the factory to create new objects. * @param validator the validator to validate * the re-usability of returned objects. * * @return an object pool bounded by <tt> size </tt> */ public static < t > pool < t > newboundednonblockingpool( int size, objectfactory < t > factory, validator < t > validator) { return new boundedpool < t >(size, validator, factory); } }
现在我们的客户端就能用一种可读性更强的方式来创建对象池了:
package com.test; import java.sql.connection; import com.test.pool.pool; import com.test.pool.poolfactory; public class main { public static void main(string[] args) { pool < connection > pool = poolfactory.newboundedblockingpool( 10, new jdbcconnectionfactory('', '', '', ''), new jdbcconnectionvalidator()); //do whatever you like } }
以上就是使用java实现一个通用并发对象池的代码分享的详细内容。
