0

Should I use synchronize when making multiple database connections and queries at the same time using java?

For example I have implemented the following method:

public static void createAccount() throws IOException, SQLException {
    DbManager.createDatabaseConnection();
    DbManager.executeSqlUpdateStatement(Account_Creation_Scripts.createAccount_Sql_Command());
    DbManager.closeDatabaseConnection();
}

The above method does its job to connect to the Database and create multiple accounts.

My plan is to use this method across multiple automation tests (Concurrently) which would run this method at the same time against the target db.

Is it good practise to implement the synchronize keyword on the following methods: createAccount, createDatabaseConnection, executeSqlUpdateStatement and closeDatabaseConnection?

Thanks

SamP
  • 417
  • 5
  • 24
  • Do you know what `synchronize` does and what it is used for? Do you know how databases handle concurrent processes? Without knowing more about your code I'd say that for the connections and statements you shouldn't need any additional synchronization as the database would handle that already (keyword: isolation). However, if your code calls this method concurrently within the same JVM there's a chance you _might_ need synchronization (depends on what your code does and what it tries to access). – Thomas Feb 06 '20 at 09:10
  • Thanks @Thomas my knowledge on synchronize is limited, I have read and researched online but have never use the synchronize practically. Currently tests are concurrently triggered from the same device which has java JDK installed etc. The framework is build using Maven and Java. – SamP Feb 06 '20 at 09:13
  • 1
    "tests are concurrently triggered from the same device" - that doesn't sound like they're running in the same JVM (instance) so you shouldn't need synchronization here - unless the tests spawn multiple threads. – Thomas Feb 06 '20 at 09:53
  • thanks @Thomas for your help, appreciate it. – SamP Feb 06 '20 at 09:57

1 Answers1

1

According to your code "DbManager" should internally have a database connection. As there are multiple calls to the DbManager, to guarantee that the same Connection object being used in all calls, you have to synchronize.

However, this is not the best approach. When you synchronize this method, only one thread is allowed to execute at a given time. Rest of the threads will have to wait which not optimal.

The best approach is to use a connection pool. 1. Get a connection from the pool 2. Execute your SQLs 3. Close the connection (this will return the connection back to the pool)

In this approach multiple threads would be able to execute simultaneously.

please check https://stackoverflow.com/a/2827719/4113311