title: How should a static database connection be initialised?
body: <p>This class is the only thing that should ever access the database and I'd like to give it a single connection object when my application starts up. However, instantiation may cause an exception to be thrown, so I can't do this:</p>
  
  <pre><code>public class DBManager {
      private static Connection conn = Database.getReadOnlyConnection();
      ...
      ...
  }
  </code></pre>
  
  <p>I have a pretty ugly workaround, and I was wondering if there's a better way.</p>
  
  <pre><code>public class DBManager {
      private static Connection conn = null;
      private static DBManager instance = null;
  
      public static DBManager getInstance() throws SQLException, ClassNotFoundException {
          if (instance == null){
              instance = new DBManager();
          }
          return instance;
      }
  
      private DBManager() throws SQLException, ClassNotFoundException {
          conn = Database.getReadOnlyConnection();
      }
  
      ...
      ...
  }
  </code></pre>
  
  <p>There's also this alternative:</p>
  
  <pre><code>public class DBManager {
      private static Connection conn = null;
      public static void setConnection(Connection conn) throws NotSupportedException{
          if (conn == null){
              this.conn = conn;
          }
          else {
              throw new NotSupportedException();
          }
      }
      ...
      ...
  }
  </code></pre>
  
  <p>Is there a nicer way of handling this in Java?</p>
  
  <p><strong>Update</strong>  </p>
  
  <p>I've decided to use a static initializer block.</p>
  
  <pre><code>public class DBManager {
      private static Connection conn;
      static {
          try {
              conn = getReadOnlyConnection();
          } catch (Exception e) {
              e.printStackTrace();
              System.exit(1);
          }
      }
      ...
      ...
  }
  </code></pre>
  
  <p>This causes the application to fail early if the database cannot be reached and avoids the problem of having to ensure that the DBManager is only being used via an instance.</p>