Archive for October, 2006

122 Transaction management Here we now see the

Thursday, October 26th, 2006

Transaction strategies 123 A code example of this is shown below: Transaction t = pm.currentTransaction(); t.setOptimistic(true); t.begin() try { String bpKey = “123″; // some valid key value BusinessPartner bp = (BusinessPartner) pm.getObjectById(bkKey); String name = bp.getName(); // bp transitions to Persistent-Nontransactional // do some work here which might take an extended time; // display the name // to the user and allow them to change it, before which // the user might go out for lunch! // retrieve the instance and update pm.refresh(bp); // bp remains Persistent-Nontransactional bp.setName(name); // bp transitions to Persistent-Dirty } catch (Exception e) { // rollback the transaction if it is still active if (t.isActive()) t.rollback(); } finally { // commit the transaction if it is still active try { // commit the transaction if it is still active if (t.isActive()) t.commit(); } catch (JDOUserException je) { // transaction rolled back advise the user that // the work they did has // not been saved and must be done again } } The instance is refreshed immediately before it is updated. The chance of concurrency assumptions being invalid is greatly reduced. However, what we have is no longer a true optimistic transaction strategy instead we have a last commit wins situation. This is equivalent to using one short-lived pessimistic transaction to read an instance, allowing the read data to be updated non-transactionally, and then committing that to the database without any regard for changes that may have occurred in the interim.
Note: If you are looking for cheapest and affordable webspace to host and run your servlet application check Astra servlet hosting services

122 Transaction management Here we now see the

Thursday, October 26th, 2006

122 Transaction management Here we now see the fundamental difference between the two approaches. In the pessimistic case, an exception at commit time might mean that the user entered data that violated integrity constraints or was otherwise invalid. If the user s data had been valid, the commit would have been successful (system failures aside). In the optimistic case, even valid data changes might be rolled back at transaction completion time, simply because the data had been changed by someone else in the interim. The user must review the now-changed data, and then perform the required changes again if they still apply. Given that the likelihood of concurrency assumptions failing is usually small, such rework is unlikely to be required often. In some cases this is acceptable if a user does go out for lunch whilst updating a business partner s details, they increase the risk of having to redo the work. They should complete the task at hand before leaving! In other cases, however, such strategies are not acceptable. Almost all server- side transactions will be pessimistic (except those which must be open across user interaction on a remote client). It is up to the designer to make an appropriate choice based upon the concurrency requirements of the system, and the cost (in terms of staff time and morale as well as any financial implications) of work needing to be redone should optimistic concurrency assumptions fail. 7.3.3 Optimistic transactions and refresh Before we look at more advanced transaction management features, I d like to mention two potential uses of the persistence manager s refresh() methods within optimistic transactions. 7.3.3.1 Last commit wins When an instance is passed as an argument to one of the persistence manager s refresh() methods, the field values are restored to those currently in the data store. After an instance has become part of an optimistic transaction, there is a possibility that the persistent entity will have been changed before the optimistic transaction is committed, causing optimistic concurrency assumptions to fail and the transaction to be rolled back. The incidence of this can be reduced if field values in an optimistically locked instance are refreshed immediately before they are updated. By retrieving field values, the optimistic currency assumptions are reset to reflect the current state of the instance. If refresh() is invoked immediately before the instance is updated and the transaction committed, then the likelihood of concurrency assumptions proving to be incorrect is greatly reduced.
Note: If you are looking for cheapest and affordable webspace to host and run your servlet application check Astra servlet hosting services

120 Transaction management catch (JDOException je) { //

Thursday, October 26th, 2006

Transaction strategies 121 whether the business partner object has been changed. This check verifies the optimistic concurrency assumptions and locks the underlying entity. 4 Assuming that the data store entity has not been changed, the updated data is synchronized to the data store and the short-lived pessimistic transaction is immediately committed. 5 The results of this commit are relayed back to the application. Thus, if the pessimistic transaction was rolled back for any reason, the application would be informed through an appropriate exception. 6 The optimistic concurrency assumptions would be false if the data was changed by someone else after the business partner was read, but before the optimistic transaction was committed. In this case, the short-lived pessimistic transaction would be rolled back and an appropriate exception thrown to the application. So that s how it works internally. Let s take a look at a code example of an optimistic transaction: Transaction t = pm.currentTransaction(); t.setOptimistic(true); t.begin() try { // do some work here which might take an extended time, // hence the use of optimistic locking. e.g. obtain a // BusinessPartner, show the field values to the user // and wait for the user to alte the data and press a // “save” button, before which the user might go out // for lunch! } catch (Exception e) { // rollback the transaction if it is still active if (t.isActive()) t.rollback(); } finally { try { // commit the transaction if it is still active if (t.isActive()) t.commit(); } catch (JDOUserException je) { // transaction rolled back advise the user that // the work they did has not been saved and must // be done again } } The only significant code differences between the two locking strategies are the setting of the Optimistic transaction property to false, and the catching of JDOUserException after commit().
Note: If you are looking for reliable and quality webspace company to host and run your servlet application check Actions servlet hosting services

120 Transaction management catch (JDOException je) { //

Thursday, October 26th, 2006

120 Transaction management catch (JDOException je) { // transaction rolled back advise the user or take // other appropriate action } } Long-lived transactions typically occur when transaction demarcation is dependent upon intervening user activity. An example would be a transaction that is held open whilst a user enters data. In such cases the use of pessimistic transactions may cause excessive locking to occur in the data store, thereby reducing the overall concurrency of the system. Although pessimistic transactions can be used in such cases, optimistic transactions provide an extremely useful alternative. 7.3.2 Optimistic transactions When working with long-lived transactions, it is often unacceptable to physically lock data in the data store for the duration. Optimistic transactions stem from an approach to increase concurrency (reduce locking) in such instances. The basis for doing this is a set of optimistic concurrency assumptions; it is presumed that any data altered in the optimistic transaction will not actually be altered by any other transaction until the first has been committed. Since in many cases this assumption is indeed true 99% or more of the time, there is no need to physically lock the underlying data. The only thing that needs to be done is to verify that the assumptions are indeed true before our changes are actually written to the data store. A typical optimistic transaction under which a BusinessPartner is to be changed, and which is executed against a database that does not provide native support for optimistic transactions, would have the following steps (for those data stores which do support optimistic transactions, these steps would conceptually still apply but the implementation would be much simpler): 1 Read the business partner from the data store and obtain some piece of information by which we can later tell whether this object has had changes committed to the data store; this typically involves a timestamp or an object version number. Where the database schema has been previously dictated it may not be possible for such version number or timestamp information to be added to the tables. In these cases the entire state of the data store entity may be used for comparative purposes. (Where the data store natively supports optimistic transactions there will be no need for this additional information.) 2 Allow the business partner to be updated. These updates may occur over a period of time, during which the corresponding data store entity is not locked. 3 When the transaction is finally committed, a short-lived pessimistic transaction is started on the underlying data store. The data store is checked to determine
Note: If you are looking for reliable and quality webspace company to host and run your servlet application check Actions servlet hosting services

118 Transaction management 7.2 Transaction interface A JDO

Thursday, October 26th, 2006

Transaction strategies 119 7.3 Transaction strategies JDO supports two specific transaction strategies. Pessimistic transactions are a required feature of the specification, and are therefore supported by all compliant implementations. Optimistic transactions are an optional feature of the specification. They will be supported by many, but not all, implementations. Support for this feature does not depend on native support for optimistic transactions in the underlying data store vendors may choose to simulate this feature where such native support is lacking. 7.3.1 Pessimistic (data store) transactions Pessimistic transactions are the default in JDO. They are suitable when the transaction is very short-lived, typically because there is no user interaction or other blocking activity between the transaction s start and end. When data is read or changed during a pessimistic transaction, other transactions are excluded from accessing that data until the first transaction has been completed. Pessimistic JDO transactions are usually implemented through native pessimistic transactions in the underlying data store. We have already seen examples of pessimistic transactions in previous chapters any transaction begun with the optimistic property of the transaction set to false is a pessimistic transaction. In the example below, a pessimistic transaction is used to undertake an element of work. If any exceptions occur while the work is being performed, the transaction is rolled back if it is still active. Transaction t = pm.currentTransaction(); t.setOptimistic(false); // I m being explicit in case it was // previously set true t.begin() try { // do some work here which does not involve significant // delays, therefore // this is a short-lived transaction // eg. Obtain a BusinessPartner and immediately update it } catch (Exception e) { // rollback the transaction if it is still active if (t.isActive()) t.rollback(); } finally { try { // commit the transaction if it is still active if (t.isActive()) t.commit(); }
Note: If you are looking for good and high quality web space to host and run your java application check Vision java hosting services

118 Transaction management 7.2 Transaction interface A JDO

Thursday, October 26th, 2006

118 Transaction management 7.2 Transaction interface A JDO persistence manager has at most one active transaction at any point in time. The PersistenceManager interface defines the currentTransaction() method, which returns an instance of the transaction interface. This transaction instance is the application developer s means for demarcating transaction boundaries within JDO. From the time a persistence manager is obtained until the time it is closed, calls to currentTransaction() will return the identical Transaction instance. Thus it is common practice, in single-threaded client-server applications that typically maintain a single persistence manager instance for an extended period, to obtain the transaction as soon as the persistence manager is available. This object is then used for transaction demarcation until the persistence manager is finally closed. During this time many independent JDO transactions may be started and completed one after the other through the single Transaction instance. Those applications that require multiple independent transactions to be active simultaneously must employ a corresponding number of persistence managers. Finally, JDO does not support the concept of nested transactions. The UML notation of the transaction interface is shown in Figure 7.1. interface Transaction +begin( ):void +commit( ):void +rollback( ):void +isActive( ):boolean +setNontransactionalRead(nontransactionalRead:boolean):void +getNontransactionalRead( ):boolean +setNontransactionalWrite(nontransactionalWrite:boolean):void +getNontransactionalWrite( ):boolean +setRetainValues(retainValues:boolean):void +getRetainValues( ):boolean +setRestoreValues(restoreValues:boolean):void +getRestoreValues( ):boolean +setOptimistic(optimistic:boolean):void +getOptimistic( ):boolean +setSynchronization(sync:Synchronization):void +getSynchronization( ):Synchronization +getPersistenceManager( ):PersistenceManager Figure 7.1 UML for Transaction interface
Note: If you are looking for good and high quality web space to host and run your java application check Vision java hosting services

116 Primary interfaces and classes interfaces of components,

Wednesday, October 25th, 2006

Transaction management Effective transaction management is a critical aspect of object persistence. This chapter discusses JDO transactions in the context of the non-managed environment. Chapter 11, contains in-depth discussions of transaction management in the managed environment. 7.1 Transactions A transaction is a grouping together of work typically changes to persistent data that must be completed in its entirety or not at all. The fundamental aim of a transaction is to ensure that partial completion, where some data changes persist in the data store and others in the same transaction don t, does not occur. This so-called atomic property of transactions is integral to the maintenance of data integrity. Another fundamental property of transactions is that they must be isolated, to a given degree, from each other. Isolation levels dictate the consistency with which data, being manipulated in one transaction, is presented, in the context of another transaction. Experienced database programmers will be familiar with the four transaction isolation levels that are recognized by JDBC: Read Uncommitted, Read Committed, Repeatable Read, and Read Serializable. Some database products, particularly object databases, define much richer sets. JDO does not explicitly specify the isolation level that will be applied. instances may have fields read at different times and, conceivably, from different data sources. Developers should not rely on any isolation level greater than Read Committed. For reference, Read Committed is defined as: This isolation level does not allow other transactions to see state changes made by this transaction until a commit has been issued. Nothing in JDO actually specifies that the locking of data in the data store should take place. Locking strategies do, however, account for the most common method of implementing the Read Committed level of isolation.

Hint: If you are looking for very good and affordable webspace to host and run your tomcat hosting application check Virtualwebstudio tomcat web hosting provider

116 Primary interfaces and classes interfaces of components,

Wednesday, October 25th, 2006

116 Primary interfaces and classes interfaces of components, and no dependency of an application on PersistenceCapable should be tolerated. What s next? In the next chapter we consider transaction management and the JDO Transaction interface. Specific focus is given to optimistic transaction strategies.

Hint: If you are looking for very good and affordable webspace to host and run your tomcat hosting application check Virtualwebstudio tomcat web hosting provider

114 Primary interfaces and classes interface Extent +iterator(

Wednesday, October 25th, 2006

PersistenceCapable 115 Candidate Class: BusinessPartner Has Subclasses: true PersistenceManager getPersistenceManager() This method returns a reference to the persistence manager from which the extent was obtained. void close(Iterator i) This method closes an Iterator previously obtained from the Extent. Subsequent to this, the iterator s hasNext() method will return false. However, the extent can still be used to obtain further iterators or as the candi date collection for queries. void closeAll() This method closes all open (i.e. not yet closed) Iterators that have been pre viously obtained from the extent. Iterator iterator() The Iterator returned from this method can be used to iterate through the contents of the extent. The objects returned at each call to the iterator s next() method will be persistent JDO instances of the candidate class or sub classes thereof. 6.6 PersistenceCapable JDO is split into two packages. Package javax.jdo is the API and contains classes and interfaces that applications will use. Package javax.jdo.spi is the SPI containing those classes and interfaces internal to JDO implementations. The PersistenceCapable interface, which is implemented by hand coding or by enhancement by all persistence-capable classes, is part of the SPI. The operations present in the PersistenceCapable interface all have names beginning with jdo . Thus, to avoid potential conflicts, you should not use this prefix for methods in your persistence-capable classes. These methods allow the persistence infrastructure to interrogate and manipulate persistent field values and perform a number of administrative functions, such as state interrogation. Application developers should never make use of the PersistenceCapable interface. All of the functionality they require is available through the PersistenceManager interface and the JDOHelper class. Indeed, even the name and structure of the PersistenceCapable interface represent implementation choices internal to JDO. The principle of encapsulation dictates that applications maintain a clear separation between the external and internal
Note: If you are looking for best hosting provider to host and run your tomcat application check Astra tomcat hosting services

114 Primary interfaces and classes interface Extent +iterator(

Wednesday, October 25th, 2006

114 Primary interfaces and classes interface Extent +iterator( ):Iterator +hasSubclasses( ):boolean +getCandidateClass( ):Class +getPersistenceManager( ):PersistenceManager +closeAll( ):void +close(it:Iterator)void Figure 6.3 UML for extent interface The extent interface (Figure 6.3) contains the following methods. boolean hasSubclasses() True is returned if subclasses were included in the call to getExtent(). Note that this does not mean that the extent necessarily contains any instances of subclasses. Consider the code extract below: Extent e = pm.getExtent(BusinessPartner.class, true); System.out.println(”Has Subclasses: ” + e.hasSubclasses()); The output printed will be: Has Subclasses: true However, the extent will contain subclasses of BusinessPartner only if such persistent instances actually existed in the data store. If hasSubclasses() returns true, the extent can be considered complete (any persistent instances of subclasses will be present). If false is returned, the extent might not be complete. Class getCandidateClass() This method returns the class descriptor of the candidate class (the class identified in the call to the persistence manager s getExtent() method). The example below uses this to determine further information about an extent. public void printExtentInfo(Extent e) { System.out.println(”Candidate Class: ” + e.getCandidateClass().getName()); System.out.println(”Has Subclasses: ” + e.hasSubClasses()); } If invoked with the extent of BusinessPartner constructed above, the output would be:
Note: If you are looking for best hosting provider to host and run your tomcat application check Astra tomcat hosting services