Transactional Queue Class Example
Example 6.2. Class TransactionalQueue public TransactionalQueue (Uid u) { super(u); numberOfElements = 0; } The constructor that creates a new persistent object is similar: public TransactionalQueue () { super(ObjectType.ANDPERSISTENT); numberOfElements = 0; try { AtomicAction A = new AtomicAction(); A.begin(0); // Try to start atomic action // Try to set lock if (setlock(new Lock(LockMode.WRITE), 0) == LockResult.GRANTED) { A.commit(true); // Commit } else // Lock refused so abort the atomic action A.rollback(); } catch (Exception e) { System.err.println(“Object construction error: “+e); System.exit(1); } } The use of an atomic action within the constructor for a new object follows the guidelines outlined earlier and ensures that the object’s state will be written to the object store when the appropriate top level atomic action commits (which will either be the action A or some enclosing action active when the TransactionalQueue was constructed). The use of atomic actions in a constructor is simple: an action must first be declared and its begin operation invoked; the operation must then set an appropriate lock on the object (in this case a WRITE lock must be acquired), then the main body of the constructor is executed. If this is successful the atomic action can be committed, otherwise it is aborted.