DEV Community

HarmonyOS
HarmonyOS

Posted on

How to handle database handle resource overload exceptions?

Read the original article:How to handle database handle resource overload exceptions?

Context

There are three common reasons for database handle resource overload:

  • Database resources were not released in a timely manner.
  • A transaction was started, but was not committed or rolled back in time.
  • Open multiple database links in a multi-threaded scenario.

The elements in the database operation class are neither static nor single-instance. Each database operation requires the creation of an entity class. This also generates a database object, RdbStore, which is not released promptly after the operation. Consequently, frequent database operations can cause handle resource overload exceptions.

Description

An imperfect resource release mechanism failed to adhere to the "open-close" pairing principle, particularly during high-frequency operations, resulting in a failure to reuse connections.

Impact: The accumulation of unclosed connections eventually triggered a system resource overload exception.

Solution

Solution 1: Release RdbStrole in time. The code example is as follows:

let db: relationalStore.RdbStore | null = null;
try {
  db = await relationalStore.getRdbStore (context, config);
   // Perform database operations 
} catch (err) {
   console.error ( "Operation failed: ", err ) ;
} finally {
  if (db) {
    db.close (); // Make sure to close 
    db = null ;
  }
}
Enter fullscreen mode Exit fullscreen mode

Solution 2: Create a globally unique database instance RdbStore to avoid multiple creations. The code example is as follows:

class DatabaseManager {
  private static instance: relationalStore.RdbStore | null = null;

  static async getInstance(context: Context) {
    if (!this.instance) {
      const config = { name: 'main.db', securityLevel: relationalStore.SecurityLevel.S3 };
      this.instance = await relationalStore.getRdbStore(context, config);
    }
    return this.instance;
  }

  static close() {
    if (this.instance) {
      this.instance.close();
      this.instance = null;
    }
  }
}

// Use 
const db = await  DatabaseManager . getInstance (context);
Enter fullscreen mode Exit fullscreen mode

Key Takeaways

  • Be sure to release database resources.
  • Create a globally unique database instance RdbStore to avoid multiple creations.

Written by Mehmet Karaaslan

Top comments (0)