Optimistic
Locking pattern for EJBs - JavaWorld July
2001
Tutorial Details:
Optimistic Locking pattern for EJBs
Optimistic Locking pattern for EJBs
By: By Yasmin Akbar-Husain and Eoin Lane
Deploy transactionally safe EJB code
s a developer, you strive to provide both functionality and performance to your users. With that in mind, how do you ensure that your consideration for performance does not compromise data integrity?
Enterprise applications often try to balance application scalability with concurrency considerations. You can achieve scalability using many different techniques, including minimizing network traffic, which often manifests itself in the Value Object pattern. Using this pattern, however, raises data integrity issues, which we will address here.
This article describes the Optimistic Locking pattern. It begins with a transactional overview, then describes the data integrity problem in detail. Next, it considers a number of solutions, focusing on a specific solution illustrated with an example.
Transactional overview
Transactions represent a fundamental unit of work for managing business complexity. At its most basic, a transaction is an execution of a program (updating a customer record in a database or making a reservation, for example). A typical business application has many associated transactions.
Transactions ensure the integrity of an application's business rules, a process that gives rise to transaction processing (TP) applications that execute multiple transactions simultaneously. A TP application creates, executes, and manages transactions, and also provides a scalable, distributed environment in which they can run.
As a TP application example, consider an airline reservation system. (One of the first TP applications was an airline reservation system called Sabre built by IBM for American Airlines.) In our example, when a passenger wants to book a seat on a flight, three things must happen:
An open seat must exist on the flight
A ticket must be issued
The passenger must be billed via a credit card using Electronic Data Interchange (EDI)
This system quickly raises concurrency, scalability, and consistency concerns when multiple users try to make reservations on a distributed system.
To simplify the potential complexity, consider the entire flight booking process as one unit of work -- a transaction. A transaction comprises four critical properties:
Atomic
Consistent
Isolated
Durable
Together, the four critical properties produce the ACID acronym.
In the context of our example, consider a transaction atomic if it executes either completely or not at all. For example, if no seat exists on the plane, the entire transaction aborts or rolls back to the transaction's start. When a transaction rolls back, the database returns to the state it had prior to the transaction's inception.
Moving on, consider a transaction isolated if the transaction executes serially. In other words, it should appear as if the transaction runs alone with no other transaction occurring simultaneously. This guarantees data integrity.
A transaction must also be durable; a permanent record of the transaction must persist. This may sound obvious, but for optimization purposes transactional records are often kept in memory. However, the transaction cannot be considered ACID until the data is written to permanent storage.
Although second on the list, the last term of an ACID transaction to consider is consistent. A transaction ensures consistency if it is atomic, isolated, and durable. If an airplane possesses 10 seats and each seat sells for $100, then at the end of 10 successful transactions the airline's account should have $1,000 more than it did when it started. If this is the case, the database is in a consistent state.
Transactions in EJBs
EJBs specifically support distributed transactions. Two types of transaction handling exist: bean-managed and container-managed transactions. The two types simplify the deployment of transactionally aware EJBs.
Bean-managed transactions in EJBs are controlled via the Java Transactional API (JTA) and explicated with the javax.transaction.UserTransaction interface -- the visible part of JTA.
The UserTransaction interface represents a contract between the client and the transactional coordinator. Explicitly, this involves three UserTransaction -defined methods:
begin()
commit()
rollback()
You can demark EJB transactions in three ways:
By the client
By an EJB
By a container
Demark by the client
A client using an EJB can explicitly demark the transaction. All the operations called between the begin() and commit() methods are involved in the transaction. In the event that any one of these operations fails, the transaction will roll back and the database will return to its initial state. Otherwise, the transaction will commit and the changes become permanent.
Demark by an EJB
As mentioned above, transaction in EJBs can be bean managed or container managed.
You can only use bean-managed transactions with session beans. Session beans use a technique similar to that of the client-managed transactions, described above, to explicitly demark transactional boundaries. Stateless session beans are restricted because they can demark transactions only within a single method, whereas stateful session beans can demark transactions across multiple methods.
Demark by a container
Both entity beans and session beans can demark transactions with container-managed transactions. In this case, you define a method's transaction attributes in an XML deployment file. This is the preferred way to define transactional behavior with EJBs. You can manage changes in transactional behavior by modifying deployment descriptors, thus minimizing propagation of code changes. There are six different transactional attributes that can define a method's transactional behavior:
Not supported
Supports
Required
Requires new
Mandatory
Never
For a full description of each attribute, see the EJB Specification in Resources . For the purposes of this article, we'll explain the Required attribute. Bean methods marked with Required must be invoked within a transaction's scope. If a transaction already exists (that is, the method is called from a client as part of an existing transaction), the Required bean method is included in the scope of the current transaction. If it is not called within the context of a transaction, then a new transaction scope is created and the Required bean method is added to that new transaction.
The problem
Optimistic data locking relies on the idea that data remains unmodified while it is away from the server. As a simple example, consider how you'd update client details. Customer details live in a row of a database (to a first approximation) and are represented by an entity bean. If a client wants to update these details in an manner that cuts down on network traffic, all the clients' details will be packaged inside a state holder object and sent back as a serialized object. This is known as the Value Object pattern. The data is not locked and other clients can have access to it simultaneously, thus ensuring a scalable system.
The problem: the customer details are away from the source and can possibly become stale. For example, a second client can request the same customer details, modify them, and commit them back to the entity beans, which will flush the data to the database. The first client, unaware that it is dealing with a stale copy of the data, modifies and commits the data. Obviously, with no checking mechanism to detect this conflict, the first client's changes, which commit last, will be made permanent, thus overwriting the changes made by the second client.
For optimistic locking to work effectively, you must be able to detect these write-write conflicts and to make the client aware of them so they can be dealt with appropriately.
Transaction solution
In designing distributed multiuser applications, sharing objects in real time is essential, but it can lead to resource sharing conflicts. In such conflicts, a user or process can change an object's state while another user or process is using the object. Database managers solve this problem using various locking strategies.
You can employ one of two types of locking strategies: pessimistic or optimistic locking. With pessimistic locking, data is locked on the database when read for update. This can lead to high lock contention. In contrast, optimistic locking lets different transactions read the same state concurrently and checks data integrity only at update time.
A long transaction performs a series of DBMS commands that extend over a long period -- hours, days, weeks, or even months. A short transaction, in contrast, resolves a group of DBMS commands within a few seconds. For applications built with EJBs, short transactions are the default model. Long transactions are possible using EJBs, but an application using them can no longer take advantage of EJB's built-in transaction management. Instead, the application must use client-initiated transactions and the UserTransaction interface to manage its own transactions, thus paying penalties in system scalability.
However, the short transaction model can simulate long transactions using either a pessimistic or optimistic locking strategy.
Transactions concerned only with simulating an exclusive lock on a shared data object use the pessimistic locking strategy. In contrast, optimistic locking involves checking data integrity only at update time. The second strategy proves most effective and acts as the basis for our discussion.
Optimistic locking support for entities is not part of the EJB specifications. Some applications servers support optimistic locking, but it's a mistake to rely on any one mechanism. A portable solution is definitely preferable.
So how does an application detect write-write conflicts? Before trying to commit changes, an application must reread the objects read earlier and determine whether t
Read
Tutorial at: Click here to view the tutorial
Rate Tutorial: Optimistic
Locking pattern for EJBs - JavaWorld July
2001
View Tutorial: Optimistic
Locking pattern for EJBs - JavaWorld July
2001
Related
Tutorials:
|
Displaying 1 - 50 of about 346 Related Tutorials.
|
Locking Issues
Locking Issues, Internal Locking Methods, External Locking
Locking Issues
 ... for table contents by using Locking :
Internal Locking can be performed in the MySQL |
JAVA JAZZ UP - Free online Java magazine
Around the Globe
Sun released Java SE 6 Update 2 on 16 July 2007... as standard Java components or
EJBs).
 ... object instances. Creational design pattern tries to reduce the creational |
Design Pattern
Design Pattern
Design Pattern
 ...;
?Pattern?
word suggests a series of events occurring in a definite order. Many... earlier,
by people frequently). This solving technique gradually becomes a pattern |
MySQL Transactional and Locking Statements
MySQL Transactional and Locking Statements, Start Transaction
Commit... and Locking Statements
 ...
The general syntax for locking and unlocking the tables
is:
LOCK TABLES tbl_name |
Matching Pattern using Regularexpression
Matching Pattern using Regularexpression
Matching Pattern using Regularexpression
 ... to match a pattern with the text by using
Regularexpression.The steps involved |
Compiling a Pattern with Multiple Flags
Compiling a Pattern with Multiple Flags
Compiling a Pattern with Multiple Flags
 ... how to compile a pattern
with multiple flags like multiline, case insensitivity |
Design patterns interview questions3
;ade pattern?
Ans. This pattern hides the complexity of business components... which reduces the remote method overhead. This pattern fits well with declarative transactions and security management.
Q18. What is Value Object Assembler pattern |
Pattern and Matcher
Java: Pattern and Matcher
Java: Pattern and Matcher
In addition to the regular expression methods... pattern can be reused by many Matcher
objects.
Pattern pat |
Compiling a Pattern with Multiple Flags
Compiling a Pattern with Multiple Flags
Compiling a Pattern with Multiple Flags
 ... how to compile a pattern
with multiple flags like multiline, case insensitivity |
Factory Pattern
Factory Pattern
Factory Pattern
 .... Factory Pattern:
One of the goals of object-oriented design..., not what kind of subclass
to create.
Creational design pattern , more |
Pattern resetting using regular expression
Pattern resetting using regular expression
Pattern resetting using regular expression
 ... are going to make program named Pattern_Resetting.java. The steps
involved in program |
Singleton Design Pattern
Singleton Pattern Java,Singleton Design Pattern,Java Singleton Design Pattern Example
Singleton Design Pattern... in java.
The Singleton design pattern ensures that only one instance |
Escaping Special Characters in a Pattern
Escaping Special Characters in a Pattern
Escaping Special Characters in a Pattern
  |
Escaping Special Characters in a Pattern
Escaping Special Characters in a Pattern
Escaping Special Characters in a Pattern
  |
EasyEclipse Server Java
Java applications, such
as JavaServer Pages, EJBs and Web Services.
EasyEclipse |
Ensemble Glider for Eclipse
J2EE application development and debugging. Create
and test EJBs and JSPs without...-time environment for EJBs, JSPs and other J2EE
components. Glider?s runtime |
Using the Captured Text of a Group within a Replacement Pattern
Using the Captured Text of a Group within a
Replacement Pattern
Using the Captured Text of a Group within a
Replacement Pattern
  |
Using the Captured Text of a Group within a Replacement Pattern
Using the Captured Text of a Group within a
Replacement Pattern
Using the Captured Text of a Group within a
Replacement Pattern
  |
Definition of Bioinformatics
;
About Bioinformatics
In February 2001, the human genome was finally... for Biotechnology Information (NCBI
2001) defines bioinformatics as:
" |
This series of progressive examples shows a typical pattern for building simple applications with a window.
NotesAbout Examples
This series of progressive examples shows a typical pattern... beginning of the pattern that will
be used in many examples in these notes.
Example - ToUppercase is an application that
extends the above pattern |
JDO Implementations
in your code, you can define timers, locking policies, queries, fetch policies... benefits:
a.) Possible choice of optimistic or pessimistic transaction mode
b.) Locking managed by Speedo itself or by the database (clustering support |
What is Persistence Framework?
database integrity. Optimistic locks are used for inter-transaction locking... and running successfully in many commercial installations since 2001.
 ....
SimpleORM takes great care with database semantics. Locking, quality |
Java EJB 3.0 Tutorials
|
About Examples
pattern for building
simple applications with a window.
Example - First Window.... This is the real beginning of the pattern that will
be used in many examples... pattern to build a running program with labels,
text fields, and buttons |
Model-View-Controller (MVC) Structure
the the Model-View-Controller (MVC)pattern.
The idea is to separate the user interface...), an Observer pattern (listeners) may be
required.
Main program
The main program...-mvc/CalcMVC.java -- Calculator in MVC pattern.
// Fred Swartz -- December 2004 |
String Regex Methods
Java: String Regex Methods
Java: String Regex Methods
In addition the the Pattern and Matcher classes,
there is some support for regular expressions in the String
class |
Design patterns interview questions
patterns interview questions1
A pattern is a proven (and recurring)
solution to a problem in a context. Each pattern describes a problem... interview questions3
This pattern hides the complexity
of business |
Design patterns interview questions
patterns interview questions1
A pattern is a proven (and recurring)
solution to a problem in a context. Each pattern describes a problem... interview questions3
This pattern hides the complexity
of business |
Hibernate Training
Examples: Using Transaction API
Locking Examples
Examples: Implementing optimistic locking
with versioning
Day 3 |
Design patterns interview questions1
patterns?
Ans. A pattern is a proven (and recurring) solution to a problem in a context. Each pattern describes a problem which occurs over and over again... and used over and over becomes a design pattern.
Q2. Can we always apply |
JSF Architecture
;
JSF was developed integrating MVC design pattern so... we need
to understand what is MVC design pattern, how MVC helps to design... design pattern splits an application design into three
separate parts:
  |
Design patterns interview questions2
pattern?
Ans. Provides a solution for pre-processing and post-processing a request... and responses. For ex. Servlet filters.
Q10. What is Front Controller pattern?
Ans... Helper pattern?
Ans. There generally are two parts to any application &ndash |
Filling Color in Excel Using JSP
to create a sheet and
then fill background color ,pattern... to fill the pattern how it look like.
setFillBackgroundColor(HSSFColor.RED.index...;HSSFColor.TURQUOISE,HSSFColor.VIOLET ,HSSFColor.WHITE,HSSFColor.YELLOW
And the pattern fields |
Time Format Example
. In this program we use a pattern of special characters to time format.
Description |
Second Format Example
. In this program we use a pattern of special characters to time format |
Minutes Format Example
. In this program we use a pattern of special characters to time format |
Day Format Example
. In this program we use a pattern of special characters to day format.
Description |
Parsing Date Example
. In this program we use a pattern of special characters to time format.
Description |
Month Format Example
. In this program we use a pattern of special characters to Month format |
Hour Format Example
. In this program we use a pattern of special characters to time format.
Description |
Java get decimal value
to the specified string pattern.
DecimalFormat dec = new DecimalFormat... format pattern. Here is the full example code
for GetDecimalValue.java |
TimeZone Format Example
class. In this program we use a pattern of special characters to time format |
Parsing Date And Time Example
and time using Format class. In this program we use a pattern of special characters |
Week Days Format Example
class. In this program we use a pattern of special characters to format week |
Year Format Example
. In this program we use a pattern of special characters to format week day |
JavaScript test() method
. The test() method returns true if a pattern exists within a string, otherwise... in the given example, we have used RegExp in order to search the specified
pattern... pattern('@') exists in the Email ID or not.
Here |
Date Format Example
. In this program we use
a pattern of special characters to date and time format |
SME Server 7.0 Pre 2 has been released now
a solid, easy-to-use server for their small-business customers. In July 2001, e-smith |
Show Stroke with Effect
in a color gradient pattern. The class Rectangle2D provides the
rectangle figure.
Following code shows the simple rectangle filled with color gradient
pattern.... The setPaint(gradientPaint)
paints the rectangle in a gradient pattern |
TOM Eclipse Plugin
;
The way to use a Pattern Matching Programming
Language |
|
|
|