在java web系统中,我想在系统启动时创建100个数据库连接,这100个连接放在vector中, 
Java代码 
public static ConnPool getCP() {   
    if (cp == null) {   
        return new ConnPool();   
    } else {   
        return cp;   
    }   
}   public static ConnPool getCP() {
if (cp == null) {
return new ConnPool();
} else {
return cp;
}
}但系统启动和访问数据库时会调用上面的方法,系统启动时cp==null,但访问数据库时cp也为null,我想是不是因为cp被jvm回收了. 
我应该怎样保证ConnPool在系统启动被实例化一次,其它访问数据库时仍然用这个实例,不用在new ConnPoll。
ConnPool 如何保持在web系统中只有一个实例呢? 
为什么每次getCP时,都会new ConnPool();   ? 

解决方案 »

  1.   

    描述不是很清楚,但感觉是不是要这样啊:public static ConnPool getCP() {
    if (cp == null) {
    cp = new ConnPool();
    return cp;
    } else {
    return cp;
    }
      

  2.   

    1 楼说的完全正确啊, 
    【return new ConnPool();  】 只是创建了一个匿名对象并将其返回,但是没有将这个引用赋给 【cp】, 所以你下一系回来的时候【cp】当然是null啦
      

  3.   

    代码改善一下
    public static ConnPool getCP() {
    ConnPool cp;
    if (cp == null) {
    cp=new ConnPool();
    return cp;
    } else {
    return cp;
    }
      

  4.   

    用单例模式可以做到,
    而单例模式有分为两种,一种饿汉式:在类加载的时候即完成对象创建,保证始终只有一个对象存在public class ConnPool {
      private ConnPool(){
      }
      private static ConnPool connPool=new ConnPool();
      public static ConnPool getCP() {  
         return connPool;
      }   
    }
    一种懒汉式:在需要时创建,且保证唯一(需要考虑线程安全)public class ConnPool{
      private ConnPool(){
      }
      private static ConnPool connPool=null;
      public static ConnPool getCP(){
        if(connPool==null){
          synchronize(ConnPool.class){
            if(connPool==null){
              connPool=new ConnPool();
            }
          }
        } 
        return connPool;
      }
    }
      

  5.   

    写错一个关键字synchronize=》synchronized
      

  6.   

    就是要用到单例模式,我感觉饿汉式的效率比较高,
    因为对于懒汉式的单例模式,只有第一次调用该方法时,synchronized(ConnPool.class){};才会
    起到作用,而这一段同步代码是需要资源的.
    这是我的理解.
      

  7.   

    为什么要线程安全。必须吗? 
    public class ConnPool {
    private static Vector conections;
    private static ConnPool cp = null;
    ...
    }
    Vector里都是connections。
    还有
        if(connPool==null){
          synchronize(ConnPool.class){
            if(connPool==null){
              connPool=new ConnPool();
            }
          }
        } 
    有必要两次判断connPool==null吗?