开发者

Java - Memory Management / DB connections question

I'm 开发者_JAVA百科writing a DB connection pool in Java. It's just a class that holds a bunch of connections and gives them out.

Do I need some kind of destructor method so that the DB connections will be closed when an instance of my class goes out of scope?

Edit: This is for learning purposes only. I would definitely use a reliable, open source connection pool in production use. I really just want to understand the memory management implications.


If you are trying to do this for learning purposes then what you are doing is fine. Download the source code for one of the below mentioned libraries and browse through their code. That would help you in understanding how are they handling the life-cycle of a connection.

But if you want to use it as part of a production application then I'd highly recommend to use one of the below

  1. BoneCP
  2. c3p0


Just off the top of my head, say you have an object, your key. Implement a unique identity for your key. hashCode() is a good place to start. When you create your object, place the object in a WeakReference and associate it to a ReferenceQueue. Now use the hashCode as the key to a Map<int, Connection>. When your object goes out of scope, go to the ReferenceQueue to retrieve the object, use the hashCode to get the Connection from the Map and close it.

See tutorial on references here


The correct way to do it is to wrap the connection instance in your own class which implements java.sql.Connection, then give that "Connection" out through the pool. You will be forced to implement all of the methods which you can happily pass on to the "real" connection. Except for one - close(). In this method you should return the connection to the pool without closing it.

You can't have an object returned to the pool by just letting it go out of scope. You can put something in finalize() which returns it to the pool, but doing this is dangerous. Finalize() only runs once for any object, so if you put something in there to "catch" the object and prevent it from being gc'd, the finalize() will never be called on it again.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜