0

This is an example of connection pool. I think I've initialized all objects, but I get the null pointer exception. How can I fix the problem?

package hello;

public class C {

 public  static void  main(String[] args) {
     CConnectionManager con=new CConnectionManager();
     CConnection conn=new CConnection();
     conn=con.GetConnection();

 }

 public static class CConnectionManager {
  private static final int MaxConSize=10;
  private CConnection[] connections ;
  {
  connections=new CConnection[MaxConSize];
  }


  public CConnection GetConnection(){
   for(int i=0;i<connections.length;i++){
    if(1==connections[i].status){
     continue;
    }
    else if(0==connections[i].status){
     connections[i].status=1;
     connections[i].pos=i;
     return connections[i];
    }
   }

   System.out.println("No connection available,Please wait");
   return null;
  }


  public void CloseConnection (CConnection con){

      if(-1==con.pos||0==con.pos){
          System.out.println("No such connection");
      }
      else
          connections[con.pos].status=0;
  }

  public void execute(String sql){

       System.out.println(sql);
      }
}



 public static class CConnection  {
  private int status=0;
  private int pos=-1;


 }

 }






Exception in thread "main" java.lang.NullPointerException
    at hello.C$CConnection.access$0(C.java:55)
    at hello.C$CConnectionManager.GetConnection(C.java:22)
    at hello.C.main(C.java:8)
0

1 Answer 1

3

You're declaring an array of 10 CConnection (connections=new CConnection[MaxConSize];) but the elements in the array are actually null.

So when doing : if(1==connections[i].status) it throws a NPE

To fix it, instantiate your CConnection objects in the constructor :

private CConnection[] connections;

public CConnectionManager (){
   connections=new CConnection[MaxConSize];
   for(int i = 0; i < connections.length; i++){
        connections[i] = new CConnection();
   }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.