I am from Java Desktop Application background. May I know what is the best practice in J2EE, to atomic read and write a field in database. Currently, here is what I did
// In Servlet.
synchronized(private_static_final_object)
{
int counter = read_counter_from_database();
counter = some_calculation_that_shall_be_done_outside_database(counter);
write_counter_back_to_database(counter);
}
However, I suspect the above method will work all the time.
As my observation is that, if I have several web request at the same time, I am executing code within single instance of servlet, using different thread. The above method shall work, as different thread web request, are all referring to same "private_static_final_object"
However, my guess is "single instance of servlet" is not guarantee. As after some time span, the previous instance of servlet may destroy, with another new instance of servlet being created.
I also came across http://code.google.com/appengine/docs/java/datastore/transactions.html in JDO. I am not sure whether they are going to solve the problem.
// In Servlet.
Transaction tx = pm.currentTransaction();
tx.begin();
int counter = read_counter_from_database(); // Line 1
counter = some_calculation_that_shall_be_done_outside_database(counter);// Line 2
write_counter_back_to_database(counter); // Line 3
tx.commit();
Is the code guarantee only when Thread A finish execute Line 1 till Line 3 atomically, only Thread B can continue to execute Line 1 till Line 3 atomically?
As I do not wish the following situation happen.
- Thread A read counter from Database as 0
- Thread A perform calculation on counter 0
- Thread B read counter from Database as 0
- Thread A write calculation result of counter 0 (Say the result is 42) to database
- Thread B perform calculation on counter 0
- Thread B write calculation result of counter 0 (Say the result is 42) to database
What I wish is
- Thread A read counter from Database as 0
- Thread A perform calculation on counter 0
- Thread A write calculation result of counter 0 (Say the result is 42) to database
- Thread B read counter from Database as 42
- Thread B perform calculation on counter 42
- Thread B write calculation result of counter 42 (Say the result is 55) to database
Thanks you.