JDO Transaction in Google App Engine
I am reading the following tutorial
Take the following code example.
import javax.jdo.Transaction;
import ClubMembers; // not shown
// ...
// PersistenceManager pm = ...;
Transaction tx = pm.currentTransaction();
try {
tx.begin();
ClubMembers members = pm.getObjectById(ClubMembers.class, "k12345");
members.incrementCounterBy(1);
pm.makePersistent(members);
tx.commit();
} finally {
开发者_JAVA百科 if (tx.isActive()) {
tx.rollback();
}
}
Does this mean, any code block in between tx.begin and tx.commit, there will be only one process/thread can access at a time? Is the tx.being and tx.commit is similar to syncrhonized keyword? But the syncrhonized protection is extended to process level instead of thread level?
For incrementCounterBy, do we have the explicitly declare the method header as synchronized? This is to ensure in entire web environment, there is only one process can access incrementCounterBy at one time. But, is synchronized protection only applied to thread level? Does synchronized keyword help? Or it is just redundant and we shall solely depend on tx.begin and tx.commit?
No.
Yes or use the synchronized(Object) {} notation.
The transaction only gives you the possibility to rollback any changes made since tx.begin().
You also have to consider that, the ClubMembers can also be accessed from outside the synchronized block while yout transaction is ongoing.
Other functions accessing ClubMember with key "k12345" will see the old counter value until you commit.
精彩评论