简体   繁体   English

Java JDBC线程安全

[英]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 这种调用序列在Java是多线程的

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. 假设你的线程没有共享任何状态或者正确地同步共享状态,那么在查看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. 每个JDBC连接一次只能由一个线程使用,您正在执行此操作。 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. 如果他们这样做,请查看数据库的隔离级别。

If you change it a little 如果你稍微改变它

void updateDatabase() {
    getConnection
    createStatement
    executeStaement
    getResult
}

it will be definitely thread safe 它肯定是线程安全的

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM