I need to implement a pool of Sessions that are returned by an external system, so that I can reuse them quickly as soon as one is needed (creating a Session takes a while). I've worked with datasource to create a pool of database connections (DBCP from Apache), and it was an implemented solution.
What do we use in a general case to pool arbitrary objects, and are there implemented solutions, ie objects, not interfaces, to deal with the task painfully?
Second question would be, how do we test whether the Session is alive ? Is there a specific method that we override in the Object pool, that queries the Session's own methods?
The third, VERY IMPORTANT question, would be, should that object pooling object be static? A bundle of objects I extract from the system must be shared among dif开发者_Python百科ferent web applications. So, say, we extract 5 Sessions. App A queries the POOL and gets the first available Session. Now there are 4 Sessions left. Another App B starts and queries THE SAME POOL. etc The pool is shared. Among different instances of the same web app, running on the same machine.
- For a generic pool of objects, you have an Apache Commons project for that.
- For testing
that a session is alive, there are
different ways, but many of them are
unreliable. And the reliable one
(doing a query on
dual
) is slow. You can have a look at c3p0, which has that feature built-in. - As long as your many webapps are in the same WAR file, I think you'd be OK to use this static pool object. Although, personally, I prefer singletons over static objects that have anything more than utility methods and constants.
In general, I'm a big fan of Hibernate
... have you considered using it for your application? You can still make plain SQL queries through it, and it handles your pooling and caching for you.
If you are using a J2EE application server then consider building a component implementing the Java Connector Architecture (JCA). Each instance of the component accesses a single Session and you configure the container to create at most five (from your example) instances. The container manages the pool and the component's lifecycle. Additionally, all applications deployed on that application server share the component's pool.
If I remember correctly (its been a while) there is also a way to signal the container that an instance died. In this scenario, the container removes the dead instance and instantiates a new one.
Some non-J2EE application servers have support for JCA components so check into it even if you are not using a traditional J2EE container.
精彩评论