jn025
jn025

Reputation: 2895

JDBC issues with multithreading

I wanted to run new Connections and it's query executions on separate threads. I wanted to start the thread by initializing/connecting to the Connection and then wait for queries and run them in the same thread. My attempt was to start the thread and initialize the connection and then pause the thread and only resume when I call execute.

private static synchronized boolean isActive()
{
    return active;
}

private static synchronized void makeActive()
{
    active = true;
}

    public void run()
    {  
        try
        {
            if(conn == null) 
            {
                onConnect();
            }

            synchronized(this)
            {
               while(!isActive())
                {
                    System.out.println(isActive());
                    wait();
                }

                System.out.println("exec");
                onExecute();
            }
        }



        catch(InterruptedException | SQLException e)
        {
                System.out.println("exception " + e.getMessage());
        }
}

onConnect creates my Connection and onExecute is called to execute a query. I call a query outside the class which does this:

    public void execute(PreparedStatement statement, String query) throws SQLException
    {
        activeQuery               =   statement;
        makeActive();
}

Currently when I start the thread my onConnect() is getting skipped if I don't use join() and when I do get the onConnect to execute then the block after the while(!isActive()) doesn't execute so i assume that it is always waiting..

Is there a better approach to using multiple threads in JDBC in this context or are there any obvious mistakes in this code?

Upvotes: 0

Views: 186

Answers (1)

sibnick
sibnick

Reputation: 4305

Look like classic wait/notify pair:

public void execute(PreparedStatement statement, String query) throws SQLException
{
    synchronized(this){
        activeQuery = statement;
        this.notify();
    }
}

and inside run method:

  while( some_finish_cond ) {
      synchronized(this){
         while(activeQuery==null){
             this.wait();
         }
         System.out.println("exec");
         onExecute();
         activeQuery = null;
      }                  
  }

Upvotes: 1

Related Questions