Avinash
Avinash

Reputation: 13267

Java JDBC thread safety

If I have following sequence in a function

void UpdateDatabase(conn) {
    createStatement
    executeStaement
    getResult
}

Is this sequence of calls multithreading safe in Java

Upvotes: 3

Views: 2391

Answers (2)

Franz Kafka
Franz Kafka

Reputation: 10851

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.

Upvotes: 2

Evgeniy Dorofeev
Evgeniy Dorofeev

Reputation: 136122

If you change it a little

void updateDatabase() {
    getConnection
    createStatement
    executeStaement
    getResult
}

it will be definitely thread safe

Upvotes: 0

Related Questions