I write a java application that starts asynchronous threads to read and update values from the same database. Each thread gets the connection from a connection pool (c3p0). I have to prevent race conditions because I have to update entries based on their current values. So reading data with a SELECT
statement and then update it with an UPDATE
statement would cause a race condition and so it would not be thread safe. I already found some solutions how to prevent such race conditions but I still have some questions.
For example I can use kind of that UPDATE ExampleTable SET ExampleValue = ExampleValue + '5' WHERE Id = '10'
to increment values thread safe. I read that this is an atomic statement. So my first question is: Is executing a PreparedStatement
in java always thread safe? I think so because (if autoCommit is true) every single executed statement is a transaction and transactions are atomic, right? If yes, is that also the case if I call a procedure with a statement or if I put multiple queries in one statement separated through semicolons?
I also read that I can set autoCommit to false and execute multiple statements befor commiting, wich also achieves thread safety because no other statement can interrupt a transaction. Is that right?
Are there any further solutions to prevent such race conditions?
SELECT FOR UPDATE
, this way you only have one statement. If you want to execute more queries/updates orSELECT FOR UPDATE
is not an option, you need to wrap them into a transaction (of course still one connection per thread). – m0skit0SELECT counter_field FROM child_codes FOR UPDATE;
UPDATE child_codes SET counter_field = counter_field + 1;
. – stonar96