简体   繁体   中英

How does JDBC Transaction lock a table in TRANSACTION_READ_COMMITTED isolation level?

I've read this tutorial: http://docs.oracle.com/javase/tutorial/jdbc/basics/transactions.html but I think I'm still missing something.

Let us take an example:

  • Thread T1 has its own Connection
  • Thread T2 has its own Connection

So, these Threads perform a Transaction (setAutoCommit(false) on two different Connections). This Transaction executes, on a single DB Table, the following queries:

  • Select a row to read a progressive number (PN)
  • Insert a row setting the progressive number to: PN++ (what I've
    read +1)

The Progressive Number must be unique (it is Primary Key) in this Table.

Do JDBC Transactions (with TRANSACTION_READ_COMMITTED isolation level) avoid the problem that T1 and T2 read the same value of PN and both try to insert in the table the same PN++? Is the Table locked until the Insert is performed and the commit() is called?

No, in order to make sure that you always have unique number you will need to: 1) [better] change the DB field to identity/sequence/auto-number depending on DB 2) use UUID as identifier 3) [worst] lock the row for the duration of read/increment/write sequence

TRANSACTION_READ_COMMITTED will only make sure that you can read ONLY the data that is already committed to DB. Ie if you had another 200 DB operations between your

UPDATE sequence 

and

commit

other threads would not be able to read the data that you updated until you commit, so in fact it will do quite the opposite of what you want.

You could also synchronize on the application level. This would work, provided that only one method in one application is doing the increment.

private **synchronized** void increment() {
    Calendar calendar = Calendar.getInstance();
    int year = calendar.get(Calendar.YEAR);
    int current = dao.getMaxNumber(year);
    dao.insertNumber(year, current+1);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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