Transactions and Threads - PowerPoint PPT Presentation

1 / 41
About This Presentation
Title:

Transactions and Threads

Description:

Consistency ... Built in to most database systems ... Which means that a separate threads running in the same process can share variables ... – PowerPoint PPT presentation

Number of Views:27
Avg rating:3.0/5.0
Slides: 42
Provided by: smlu
Category:

less

Transcript and Presenter's Notes

Title: Transactions and Threads


1
Transactions and Threads
  • CC292
  • Simon M. Lucas

2
Relevance To Web App. Prog.
  • Web applications are multi-threaded
  • The web app server (e.g. Tomcat) allocates a
    thread to deal with each incoming request
  • Important that these threads do not interfere
    with each other
  • And that properties of a good transaction are
    maintained
  • These notes cover the necessary background
  • And show examples of Atomic transactions for db4o
    and JDBC

3
Overview
  • ACID Criteria
  • Locking mechanisms
  • Two-phase commit
  • Processes and Threads
  • Multi-threading examples
  • Coarse and Fine-Grain Locking
  • Deadlock avoidance

4
ACID Criteria
  • A good transaction should conform to the ACID
    criteria and be
  • Atomic
  • Consistent
  • Isolated
  • Durable

5
Atomicity
  • Means that a transaction is indivisible
  • Either all the statements in a transaction happen
    (are committed) or none of them do.
  • E.g. when transferring money between two
    accounts, the account being debited
  • Databases offer atomic transactions with begin ..
    commit/rollback

6
Consistency
  • A transaction should transform the system from
    one consistent state to another consistent state.
  • This is partially achieved through atomicity
  • and partially by ensuring that the transactions
    are compliant with the logical database
    constraints
  • e.g. do not introduce violations of entity or
    referential integrity or other constraints

7
Isolation
  • Each transaction should occur independently of
    other concurrently happening transations.
  • This can be achieved though locking mechanisms
    such as monitors
  • Built in to most database systems
  • Can be programmed into Java-implemented systems
    with careful use of the synchronized keyword

8
Durability
  • the effects of a transaction are stored
    permanently
  • irrespective of power failure or system
    crashes
  • Implies that transactions MUST utilise persistent
    storage mechanisms
  • E.g. either directly with the filing system, or
    more usually via a database system

9
Atomic Transactions
  • Next examples
  • Db4o
  • JDBC
  • Db4o example is more complete
  • In the example, it also appears to be more
    complex
  • Why is that?

10
Atomic transaction db4oConsider this Bank
Account class
  • public class Account
  • String name
  • int balance
  • public Account(String name, int balance)
  • this.name name
  • this.balance balance
  • public synchronized void transfer(int
    amount) throws Exception
  • if (balance amount lt 0)
  • throw new Exception("Overdraft not
    allowed
  • (balance amount))
  • balance amount
  • ...

11
Transfer between accountsBank.transfer()
  • public static void transfer(ObjectContainer db,
    Account from, Account to, int amount)
  • try
  • to.transfer(amount)
  • db.set(to)
  • from.transfer(-amount)
  • db.set(from)
  • db.commit()
  • catch (Exception e)
  • System.out.println(e)
  • db.rollback()
  • db.ext().refresh(from, 10)
  • db.ext().refresh(to, 10)

12
Example Atomic Transaction
  • Following outline example uses a JDBC connection
    to make an atomic transaction
  • Note that con is of type java.sql.Connection

13
Notes on Transfer
  • Use of commit() or rollback()
  • Similar to use of JDBC updates
  • Note also
  • db.ext().refresh(from, 10)
  • This is used to return the in-memory objects to
    their on-disk state
  • In this case, to the state they were in before
    the transaction was aborted
  • Exercise try this in the lab and check what
    happens when refresh() is omitted.

14
JDBC Transaction
  • try
  • con.setAutoCommit( false )
  • statement con.createStatement()
  • statement.executeUpdate( update1 )
  • statement.executeUpdate( update2 )
  • // to get here, both must have worked
  • con.commit()
  • catch(SQLException e) // something wrong!
  • con.rollback()

15
Threads and Processes

16
Processes v. Threads
  • Typing java MyProg creates a new process to run
    the Java Virtual Machine
  • Can have many processes running on a single
    machine
  • Each process has an independent address space
  • Which means that processes do not share variables

17
Threads
  • Each process can have many threads
  • Each thread is an independent flow of control
  • Threads DO share the same address space
  • Which means that a separate threads running in
    the same process can share variables

18
Simple Example
  • Suppose we have a static variable x defined like
    this
  • class MyClass
  • static int x 0
  • Then this line of code gets executed
  • x
  • 1) by separate processes and
  • 2) by separate threads

19
Separate Processes

x 0
x 0
x
x
x 1
x 1
20
Separate Threads
  • In the separate thread case, each thread accesses
    the same variable
  • The order in which the increments happen is
    critical to the final value of x
  • If thread 1 completes the operation before thread
    2 starts, we get a final value of x 2
  • If the operations overlap, we may get a final
    value of x 1
  • Java has the synchronized keyword to ensure
    correct operation

x 0
x
x
? x 2 ?
21
Thread Safety
  • When two or more threads overlap in accessing a
    common variable- trouble!
  • The problem arises when the reading and writing
    of the variable by one thread is interleaved by
    that of another thread
  • Now consider x getting executed concurrently by
    two threads

22
Thread Interleaving (x)

Thread1
Thread2
x
0
fetch 0
0
fetch 0
x
0
1
return 1
x
1
1
return 1
t
1
23
Synchronization
  • Java has the synchronized keyword to provide
    locking
  • This is based on Hoare Monitors
  • Each Java Object has an associated Monitor to
    provide the locking facility
  • Important to remember that the Lock is associated
    with an Object, not with a method
  • Can protect either blocks of code or methods
  • Only one thread at a time can enter the
    synchronized method or block

24
Hoare Monitors
  • Used to provide exclusive access to a block of
    code or resource (critical section)
  • Any thread entering the critical section must
    obtain go through the Monitor associated with
    that section.
  • If already occupied, the thread must wait
  • When a thread leaves the critical section, the
    monitor will pick a waiting thread
  • The waiting thread is then reactivated and may
    proceed through the that section.

25
Method Synchronization
  • At the method level
  • public synchronized void myMethod()
  • Note that the lock is associated with the Object,
    NOT directly with the method
  • But it is the access to the method that is
    protected with the lock.

26
Block Synchronization
  • Suppose we have a collection of bank account
    objects
  • Can transfer money into or out of such an object,
    using the transfer method
  • Then to transfer amount money from account a1 to
    account a2
  • synchronized (a1)
  • synchronized (a2) (
  • a1.transfer( -amount ) a2.transfer(
    amount )

27
Counter Example
  • The aim is to investigate the need for Object
    locking, and how to achieve it through method
    synchronization
  • Well develop two versions of Counter
  • With and without synchronization
  • And a program called CounterTest to test them

28
CounterTest
  • package examples.threads
  • public class CounterTest
  • public static void main(String args)
  • throws Exception
  • int n Integer.parseInt( args0 )
  • System.out.println( "Running with n " n
    )
  • utilities.ElapsedTimer t
  • new utilities.ElapsedTimer()
  • Counter c1 new Counter( n )
  • Counter c2 new Counter( n )
  • c1.join()
  • c2.join()
  • System.out.println(
  • t " counter " Counter.x )

29
Counter
  • package examples.threads
  • public class Counter extends Thread
  • static int x 0
  • int n
  • public Counter(int n)
  • this.n n
  • start()
  • // buggy version
  • public int inc()
  • return x
  • public void run()
  • for (int i0 iltn i)
  • inc()

30
Comments on Counter
  • The buggy version above does not declare the
    inc() method to be synchronized
  • This produce spurious results
  • But may also work fine for much of the time
  • Hence producing intermittent faults of the worst
    kind!

31
Counter Output
  • Cgtjava examples.threads.CounterTest 10000000
  • Running with n 10000000
  • 561 ms elapsed counter 18029280
  • Cgtjava examples.threads.CounterTest 10000000
  • Running with n 10000000
  • 571 ms elapsed counter 20000000
  • Cgtjava examples.threads.CounterTest 10000000
  • Running with n 10000000
  • 561 ms elapsed counter 20000000
  • Cgtjava examples.threads.CounterTest 10000000
  • Running with n 10000000
  • 571 ms elapsed counter 17899989

32
Synchronized Counter
  • Simply insert the keywords in bold
  • public static synchronized void inc()
  • Now get the following output
  • Cgtjava examples.threads.CounterTest 10000000
  • Running with n 10000000
  • 7020 ms elapsed counter 20000000
  • Cgtjava examples.threads.CounterTest 10000000
  • Running with n 10000000
  • 7020 ms elapsed counter 20000000

33
Why Static?
  • Without the static modifier, we synchronize on
    instances of the class
  • I.e. we have two locks one for c1 and one for
    c2.
  • Thus there is no contention for the locks, and no
    protection for the static variable x
  • With the static modifier, the lock is on the
    Counter.class object (of type Class)
  • There is only one of these in the JVM, and the
    static variable x is now properly protected

34
Performance of synchronized
  • The code now always returns the correct answer
    fixing the critical race problem of the buggy
    version
  • But it is over ten times slower than the buggy
    version!
  • Only use synchronization when you need it!
  • When you do need it, be sure to use it!

35
Synchronized Version (x)

Thread1
Thread2
x
0
fetch 0
0
x
0
1
fetch 1
return 1
1
x
2
return 2
t
2
36
Deadlock
  • Deadlock arises as follows
  • Thread 1 acquires lock on object A
  • Thread 2 acquires lock on object B
  • Thread 1 waits for lock on object B
  • Thread 2 waits for lock on object A
  • Care must be taken to ensure that this can never
    happen

37
Dining Philosophers

38
Coarse-grained Locking
  • Implementing a coarse-grained locking strategy
    for the dining philosophers is straightforward
  • The synchronization is done on the entire set of
    chopsticks
  • This prevents deadlock
  • But as we can see from running the applet,
    makes for slow eating!

39
Fine-grained Locking
  • Now we lock at the chopstick level i.e. at
    individual resource level
  • BUT need to be careful about how we request the
    locks
  • Otherwise, could end up in a state of deadlock

40
Fine-grained Deadlock Avoidance
  • Simple strategy easy to implement
  • Ensure that each thread always requests locks in
    the same order

41
Summary
  • ACID properties of a good transaction
  • Relationship to Java code
  • Ensuring isolation
  • The synchronized keyword
  • Based on Hoare monitors
  • Can make code thread-safe
  • But take care to avoid deadlock
  • Atomicity
  • commit / rollback / refresh
Write a Comment
User Comments (0)
About PowerShow.com