Upload
hop-huynh
View
216
Download
0
Embed Size (px)
Citation preview
8/8/2019 6-Concurence and Transaction
1/36
1
Transaction
Concurrency
8/8/2019 6-Concurence and Transaction
2/36
2
Transaction
8/8/2019 6-Concurence and Transaction
3/36
3
What is Transaction ?
Transaction is a unit-of-work
The primary tool for handling concurrency inapplications.
A transaction is a bounded sequence of work,with both start and end points well defined.
All participating resources are in a consistentstate both when the transaction begins and
when the transaction ends. Each transaction must complete on and all-or-
nothing basis.
8/8/2019 6-Concurence and Transaction
4/36
4
ACID - Propertiess transactions
Atomicity:
Each step in the sequence of actions performed within theboundaries of a transaction must complete successfully or allwork must roll back.
Consistency:
A system's resources must be in a consistent, noncorrupt stateat both the start and the completion of a transaction.
Isolation:
The result of an individual transaction must not be visible to any
other open transactions until that transaction commitssuccessfully.
Durability:
Any result of a committed transaction must be made permanent.This translates to "Must survive a crash of any sort."
8/8/2019 6-Concurence and Transaction
5/36
5
Lifecycle of a Transaction ?
Lifecycle of an atomic unit of worka transaction
8/8/2019 6-Concurence and Transaction
6/36
6
Declarative transaction demarcation
The application developer has to manually set transaction
boundaries, in other words, begin, commit, or rollback
database transactions himself.
Session session = sessionFactory.openSession();
Transaction tx = null;try {tx = session.beginTransaction();
// do some work
tx.commit();} catch (RuntimeException ex) {
tx.rollback();} finally {
session.close();}
8/8/2019 6-Concurence and Transaction
7/36
7
Declarative transaction demarcation
A much more flexible solution is Hibernate's built-in "current session" context management, asdescribed earlier:
8/8/2019 6-Concurence and Transaction
8/36
8
Concurrency
8/8/2019 6-Concurence and Transaction
9/36
9
What is Concurrency?
Whenever you have multiple processes or
threads, transactions manipulating the same
data, you run into concurrency problems.
Concurrency issues: Lost updates
Dirty read
Unrepeatable read
Phantom read
8/8/2019 6-Concurence and Transaction
10/36
10
Lost updates
occurs if two transactions both update a row andthen the second transaction aborts, causing bothchanges to be lost.
Lost update:two transactions
update thesame datawithout locking.
8/8/2019 6-Concurence and Transaction
11/36
11
Dirty read
Occurs if a one transaction reads changes made by
another transaction that has not yet been committed.
This is dangerous, because the changes made by the other
transaction may later be rolled back, and invalid data may be
written by the first transaction
Dirty read:
transaction A readsuncommitted data
8/8/2019 6-Concurence and Transaction
12/36
12
Unrepeatable read
Occurs if a transaction reads a row twice and reads
different state each time.
A special case is the second lost updates problem: Two
concurrent transactions both read a row: One writes to it and
commits, and then the second writes to it and commits. The
changes made by the first writer are lost.
Unrepeatable read:transaction A executestwo nonrepeatable reads
8/8/2019 6-Concurence and Transaction
13/36
13
Phantom read
Occurs when a transaction executes a query twice, and
the second result set includes rows that werent visible in
the first result set or rows that have been deleted.
This situation is caused by another transaction inserting or
deleting rows between the execution of the two queries
Phantom read:
transaction A reads newdata in the second select.
8/8/2019 6-Concurence and Transaction
14/36
14
Controlling
concurrent access
8/8/2019 6-Concurence and Transaction
15/36
15
Controlling concurrent access
Transaction isolation is tool for handling
concurrency
Isolation is a vital technique because it reduces
the chance of errors. With isolation you arrange things so that the
programs enters an isolated zone, within which
you don't have to worry about concurrency.
Good concurrency design is thus to find ways of
creating such zones and to ensure that as much
programming as possible is done in one of them.
8/8/2019 6-Concurence and Transaction
16/36
16
Transaction isolation levels
Read uncommitted
Permits dirty reads but not lost updates.
One transaction may not write to a row if another uncommitted
transaction has already written to it. Any transaction may read
any row, however.
This may be implemented in the database-management system
with exclusive write locks.
Read committed :
permits unrepeatable reads but not dirty reads.
Reading transactions dont block other transactions fromaccessing a row. However, an uncommitted writing transaction
blocks all other transactions from accessing the row.
This may be achieved by using shared read locks and exclusive
write locks.
8/8/2019 6-Concurence and Transaction
17/36
17
Transaction isolation levels
Repeatable read :
Permits neither unrepeatable reads nor dirty reads.
Phantom reads may occur.
Reading transactions block writing transactions (but
not other reading transactions), and writingtransactions block all other transactions.
Serializable
Provides the strictest transaction isolation.
Emulates serial transaction execution, as if
transactions were executed one after another,
serially, rather than concurrently.
8/8/2019 6-Concurence and Transaction
18/36
18
Choosing an isolation level
Developers are often unsure what transaction
isolation level to use in a production application
Too great a degree of isolation harms scalability of a
highly concurrent application.
Insufficient isolation may cause subtle,
unreproduceable bugs in an application that youll
never discover until the system is working under
heavy load.
Typical, there are two forms of concurrencycontrol that we can use: optimistic and
pessimistic
8/8/2019 6-Concurence and Transaction
19/36
19
Optimistic and Pessimistic
Concurrency Control Let's suppose that Martin and David both want
to edit the Customer file at the same time. With optimistic locking:
Both of them can make a copy of the file and edit it freely.
If David is the first to finish, he can check in his work withouttrouble.
Martin's commit is rejected.
With pessimistic locking: if Martin is first to check out, David can't work with the file
until Martin is finished with it and commits his changes. A good way of thinking about this is that an
optimistic lock is about conflict detection whilea pessimistic lock is about conflict prevention
8/8/2019 6-Concurence and Transaction
20/36
20
Optimistic concurrency control
The only approach that is consistent with high
concurrency and high scalability is optimistic
concurrency control with versioning.
Each entity instance has a version, which canbe a number or a timestamp.
8/8/2019 6-Concurence and Transaction
21/36
21
Version Attribute
public class Item {...private int version;...
}
public class Item {@Versionprivate int version;...
}
...
8/8/2019 6-Concurence and Transaction
22/36
22
Version Attribute
Sometimes a timestamp is preferred
public class Item {...private Date lastUpdated;...
}
...
8/8/2019 6-Concurence and Transaction
23/36
23
Hibernate provides automatic versioning.
Hibernate increments an objects version when
its modified, compares versions automatically,
and throws an exception if a conflict is detected.Consequently, you add this version property to
all your persistent entity classes to enable
optimistic locking
Hibernate checks instance versions at flushtime, throwing an exception if concurrent
modification is detected.
Automatic versioning
8/8/2019 6-Concurence and Transaction
24/36
try {
sf.getCurrentSession().beginTransaction();
// do works
sf.getCurrentSession().getTransaction().commit();
} catch (StaleObjectStateException staleEx) {
// optimistic concurrency control
} catch (Throwable ex) {
try {
if (sf.getCurrentSession()
.getTransaction().isActive()){sf.getCurrentSession()
.getTransaction().rollback();
}catch (Throwable rbEx) {
}
}
8/8/2019 6-Concurence and Transaction
25/36
25
Customizing automatic versioning
If you need optimistic locking for detached objects, youmust use a version number or timestamp.
If you dont have version or timestamp columns,Hibernate can still perform automatic versioning, but onlyfor objects that are retrieved and modified in the samepersistence context
You can enable this functionality by setting the
optimistic-lock attribute on the class mapping:
...
8/8/2019 6-Concurence and Transaction
26/36
26
Pessimistic Locking control
Hibernate will always use the lockingmechanism of the database, never lock objectsin memory!
The LockMode class defines the different lock
levels that may be acquired by Hibernate. A lockis obtained by the following mechanisms: LockMode.WRITE is acquired automatically when
Hibernate updates or inserts a row.
LockMode.UPGRADE may be acquired upon explicituser request using SELECT ... FOR UPDATE ondatabases which support that syntax.
8/8/2019 6-Concurence and Transaction
27/36
27
Pessimistic Locking
LockMode.UPGRADE_NOWAIT may be acquired uponexplicit user request using a SELECT ... FOR UPDATENOWAIT underOracle.
LockMode.READ is acquired automatically whenHibernate reads data underRepeatable Read orSerializable isolation level. May be re-acquired byexplicit user request.
LockMode.NONE represents the absence of a lock. Allobjects switch to this lock mode at the end of a
Transaction. Objects associated with the session via a call to update()
or saveOrUpdate() also start out in this lock mode.
8/8/2019 6-Concurence and Transaction
28/36
28
Pessimistic Locking
The "explicit user request" is expressed in one ofthe following ways:
A call to Session.load(), Session.get()
specifying a LockMode.
A call to Session.lock()
A call to Query.setLockMode()
8/8/2019 6-Concurence and Transaction
29/36
29
Session and transaction scopes
A SessionFactory is an expensive-to-create,threadsafe object intended to be shared by allapplication threads.
A Session is an inexpensive, non-threadsafe
object that should be used once, for a singlerequest, a conversation, single unit of work.
A database transaction has to be as short aspossible, to reduce lock contention in the
database. Long database transactions willprevent your application from scaling to highlyconcurrent load
8/8/2019 6-Concurence and Transaction
30/36
30
Using Session
Session sess = factory.openSession();Transaction tx = null;
tx = sess.beginTransaction();
// Operation
tx.commit();
sess.close();
Don't use the Session-per-operation antipattern.
Don't open and close a Session for every database call in
a single thread!
8/8/2019 6-Concurence and Transaction
31/36
31
// Server receive request from client
Session sess = factory.openSession();
Transaction tx = sess.beginTransaction();
// all database operations are executed
tx.commit();
sess.close();
//Server response
Using Session
The Session-per-requestpattern is used in amulti-user client/server application.
8/8/2019 6-Concurence and Transaction
32/36
32
Using Session
Never use the anti-patterns session-per-user-session orsession-per-application
A Session is not thread-safe.
If you keep your HibernateS
ession in yourHttpSession (discussed later), you should consider
synchronizing access to your Http session.
Otherwise, a user that clicks reload fast enough may
use the same Session in two concurrently running
threads.
8/8/2019 6-Concurence and Transaction
33/36
33
Long conversations
Example:
The first screen of a dialog opens, the data seen by
the user has been loaded in a particularSession and
database transaction. The user is free to modify the
objects. The user clicks "Save" after 5 minutes and expects
his modifications to be made persistent; he also
expects that he was the only person editing this
information and that no conflicting modification canoccur.
We call this unit of work user, a long running
conversation
8/8/2019 6-Concurence and Transaction
34/36
34
Long conversations
A first naive implementation might keep theSession and database transaction open duringuser think time, with locks held in the databaseto prevent concurrent modification, and to
guarantee isolation and atomicity. This is easier to implement than it might sound,
especially if you use Hibernate's features: Automatic Versioning: Hibernate can do automatic
optimistic concurrency control for you, it canautomatically detect if a concurrent modificationoccured during user think time. Usually we onlycheck at the end of the conversation.
8/8/2019 6-Concurence and Transaction
35/36
35
Long conversations
Detached Objects: If you decide to use thealready discussed session-per-request pattern,
all loaded instances will be in detached state
during user think time. Hibernate allows you to
reattach the objects and persist the
modifications, the pattern is called session-per-
request-with-detached-objects.
Automatic versioning is used to isolateconcurrent modifications.
8/8/2019 6-Concurence and Transaction
36/36
36
Long conversations
Extended (or Long) Session: The HibernateSession may be disconnected from the
underlying JDBC connection after the database
transaction has been committed, and
reconnected when a new client request occurs.
This pattern is known as session-per-
conversation and makes even reattachment
unnecessary. Automatic versioning is used toisolate concurrent modifications and the Session
is usually not allowed to be flushed
automatically, but explicitely.