質問

Basically i just want work only single sql connection at a time, wait other connection until first close.

Class myConnection
{
        private static Connection con=null;
        public void getConnection()
        {
            con= DriverManager.getConnection("jdbc:sqlite:"
                    + properties.getProperty("sqliteDatabase"));
        }
        public void closeConnection()
        {
         con.close();
        }
        public static void main(String s[]){
           myConnection m1=new myConnection();
           m1.getConnection();
          //m1 object using con variable
           myConnection m2=new myConnection(); 
          //m1.still executing query using con object
          m2.getConnection();
          //i should not allow m2 access con object till con object is null
}

i know it is not a right program. i just tried to explain what i want to do. In short, i want single connection should work, wait another until connection is close.

役に立ちましたか?

解決

I suggest to use http://commons.apache.org/proper/commons-dbcp/ for this purpose

BasicDataSource ds = new BasicDataSource();
ds.setUrl(url);
ds.setMaxActive(1);

now only one thread can get a connection from pool, others will block

他のヒント

You can create pool of Connection object with size 1. For example have : ConnectionProvider class.

Implement signleton pattern on Connection Class.

 Class myConnection
{
        private static Connection con=null;
        public synchronized void getConnection()
        {
            con= DriverManager.getConnection("jdbc:sqlite:"
                    + properties.getProperty("sqliteDatabase"));
        }
        public synchronized void closeConnection()
        {
         con.close();
        }
        public static void main(String s[]){
           myConnection m1=new myConnection();
           m1.getConnection();
          //m1 object using con variable
           myConnection m2=new myConnection(); 
          //m1.still executing query using con object
          m2.getConnection();
          //i should not allow m2 access con object till con object is null
}

Synchronized method can be called once at a time, No two objects can call synchronized method at the same time, If they call then one will have to wait for other.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top