title: How to avoid duplicate database connection in java?
body: <p>I have 2 classes. C_DB and C_Test.</p>
  
  <p>In C_DB, getConnection() method returns a connection. If I call getConnection() multiple times, it's gonna re-connect to the DB and return multiple connection.</p>
  
  <p>Is there a way I can avoid this? I want to check if a connection does exist, then just return that connection instead of create a new one. So there will be only 1 connection to db.</p>
  
  <p><strong>C_DB</strong></p>
  
  <pre><code>public class C_DB {
      Connection con;
  
      public C_DB() {
          String dbLink = "jdbc:mysql://localhost:3306/database";
          String dbUser = "root";
          String dbPass = "";
  
          try {
              con = DriverManager.getConnection(dbLink, dbUser, dbPass);
          } catch (SQLException e) {
              throw new IllegalStateException("DB Errors: ", e);
          }
      }
  
      public Connection getConnection() {
          return con;
      }
  }
  </code></pre>
  
  <p><strong>C_Test</strong></p>
  
  <pre><code>public class C_Test {
  
      public static void main(String[] args) throws Exception {
          Connection con1 = new C_DB().getConnection(); // new connection
          Connection con2 = new C_DB().getConnection(); // new duplicate connection
          Connection con3 = new C_DB().getConnection(); // new duplicate connection
      }
  
  }
  </code></pre>