3

If I have following sequence in a function

void UpdateDatabase(conn) {
    createStatement
    executeStaement
    getResult
}

Is this sequence of calls multithreading safe in Java

Avinash
  • 12,851
  • 32
  • 116
  • 186
  • 1
    I think you need to show us some more code snippet, like what parameters are used by `createStatement`, `executeStaement` and `getResult`. How are you calling the `UpdateDatabase` function – Apurv Apr 17 '13 at 08:40
  • Also it will depend on what database you are using as well. Typically databases will manage concurrent requests. So you wouldn't worry about thread safety at db client side. – anoopelias Apr 17 '13 at 08:45
  • possible duplicate of [Is java.sql.Connection thread safe?](http://stackoverflow.com/questions/1531073/is-java-sql-connection-thread-safe) – Sumit Singh Apr 17 '13 at 08:50
  • 1
    Just make sure every thread uses its own Connection. – Mark Rotteveel Apr 17 '13 at 08:56

2 Answers2

2

Asuming your threads don't share any state or otherwise synchronize the shared state correctly the execution is only thread safe when viewing what happens inside of the JVM. More importantly however is if your data can still be corrupted.

Every JDBC connection should only be used by one thread at a time, which you are doing. Database systems however define four isolation levels, defining which state of the data concurrent transactions can see. If your concurrent transactions don't touch the same data your fine. If they do, have a look at the isolation level of your database.

Franz Kafka
  • 10,623
  • 20
  • 93
  • 149
0

If you change it a little

void updateDatabase() {
    getConnection
    createStatement
    executeStaement
    getResult
}

it will be definitely thread safe

Evgeniy Dorofeev
  • 133,369
  • 30
  • 199
  • 275
  • Well, the question is "_Is this sequence of calls thread safe_". And not how to make this thread-safe – Apurv Apr 17 '13 at 09:05