tags:

views:

109

answers:

1

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 {
            if (tx.isActive()) {
                tx.rollback();
            }
        }
  1. 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?

  2. 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?

A: 
  1. No.

  2. 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.

Fedearne
But using synchronized(Object) {}, will only give you thread level synchronized protection, not process level. Different web request are usually re inside different process.
Yan Cheng CHEOK
Obviously Object would be either "this" or some other use full lock-object. (Not new Object())
Fedearne