title: How to thread-safely read from and write to the database?
body: <p>I'm writing a Java API, and I am using MySQL. What is the best practice for thread safe reading and writing to the database?</p>
  
  <p>For instance, take the following <code>createUser</code> method:</p>
  
  <pre><code>// Create a user
  // If the account does not have any users, make this
  // user the primary account user
  public void createUser(int accountId) {
      String sql =
              "INSERT INTO users " +
              "(user_id, is_primary) " +
              "VALUES " +
              "(0, ?) ";
      try (
              Connection conn = JDBCUtility.getConnection();
              PreparedStatement ps = conn.prepareStatement(sql)) {
  
          int numberOfAccountsUsers = getNumberOfAccountsUsers(conn, accountId);
          if (numberOfAccountsUsers &gt; 0) {
              ps.setString(1, null);
          } else {
              ps.setString(1, "y");
          }
  
          ps.executeUpdate();
      } catch (SQLException e) {
          e.printStackTrace();
      }
  }
  
  // Get the number of users in the specified account
  public int getNumberOfAccountsUsers(Connection conn, int accountId) throws SQLException {
      String sql =
              "SELECT COUNT(*) AS count " +
              "FROM users ";
      try (
              PreparedStatement ps = conn.prepareStatement(sql);
              ResultSet rs = ps.executeQuery()) {
  
          return rs.getInt("count");
      }
  }
  </code></pre>
  
  <p>Say source A calls <code>createUser</code>, and has just read that account ID 100 has 0 users. Then, source B calls <code>createUser</code>, and before source A has executed its update, source B has also read that account ID has 0 users. As a result, both source A and source B have created primary users.</p>
  
  <p>How can this situation be safely implemented?</p>