title: JDBC and Multithreading
body: <p>I am trying to run few queries using a multithreaded approach, however I think I am doing something wrong because my program takes about five minute to run a simple select statement like </p>
  
  <pre><code>SELECT * FROM TABLE WHERE ID = 123'
  </code></pre>
  
  <p>My implementation is below and I am using one connection object. </p>
  
  <p>In my run method</p>
  
  <pre><code>public void run() {
      runQuery(conn, query);
  }
  </code></pre>
  
  <p>runQuery method</p>
  
  <pre><code>public void runQuery(Connection conn, String queryString){
      Statement statement;
      try {
            statement = conn.createStatement();
            ResultSet rs = statement.executeQuery(queryString);
            while (rs.next()) {}
      } catch (SQLException e) {
          e.printStackTrace();
      }
  }
  </code></pre>
  
  <p>Finally in the main method, I start the threads using the snippet below. </p>
  
  <pre><code>MyThread bmthread = new MyThread(conn, query);
  ArrayList&lt;Thread&gt; allThreads = new ArrayList&lt;&gt;();
  double start = System.currentTimeMillis();
      int numberOfThreads = 1;
      for(int i=0; i&lt;=numberOfThreads; i++){
          Thread th = new Thread(bmthread);
          th.setName("Thread "+i);
          System.out.println("Starting Worker "+th.getName());
          th.start();
          allThreads.add(th);
      }
  
      for(Thread t : allThreads){
          try {
              t.join();
          } catch (InterruptedException e) {
              e.printStackTrace();
          }
      }
  double end = System.currentTimeMillis();
  double total = end - start;
  System.out.println("Time taken to run threads "+ total);
  </code></pre>
  
  <p>Update : I am now using separate connection for each thread.</p>
  
  <pre><code>ArrayList&lt;Connection&gt; sqlConn = new ArrayList&lt;&gt;();
      for(int i =0; i&lt;10; i++){
          sqlConn.add(_ut.initiateConnection(windowsAuthURL, driver));
      } 
  loop:
    MyThread bmthread = new MyThread(sqlConn.get(i), query);
  </code></pre>