Showing posts with label Locks. Show all posts
Showing posts with label Locks. Show all posts

(ref) On Transactions, Locks and Cursors

Oracle Locking mechanisms

  • locks prevent destructive interactions that incorrectly update data or incorrectly alter underlying data structures, between transactions accessing shared data.
  • Two types: exclusive locks and share locks.
  • Oracle's default locking mechanisms ensures data concurrency, data integrity, and statement-level read consistency.
    • A row is locked only when modified by a writer.
    • A writer of a row blocks a concurrent writer of the same row.
    • A reader never blocks a writer.(except: SELECT .. FOR UPDATE)
    • A writer never blocks a reader.


Lock modes: level of restrictiveness x degree of data concurrency
  • The less restrictive the level, the more available the data is for access by other users.
  • Exclusive lock mode:
    • Prevents the resource from being shared. Obtained for data modification.
    • The first transaction to lock a resource exclusively is the only transaction that can alter the resource until the exclusive lock is released.
  • Share lock mode:
    • Allows resource to be shared. Multiple users reading data can share the data, holding share locks to prevent concurrent access by a writer who needs an exclusive lock.
    • Several transactions can acquire share locks on the same resource.
    • If a SELECT ... FOR UPDATE selects a single table row, the transaction acquires (a) an exclusive row lock and (b) a row share table lock.
    • The row lock allows other sessions to modify any rows other than the locked row, while the table lock prevents sessions from altering the structure of the table.
    • Oracle Database never escalates locks


DML_LOCKS (init.ora)

Default: Derived: 4 * TRANSACTIONS (assumes an average of 4 tables referenced for each transaction)
Modifiable: No
Range: 20 to unlimited


Automatic Locks
  • DML Lock
    • also called data lock. Guarantees integrity of data concurrently accessed by multiple users.
    • They are either Row Locks (TX) or Table Locks (TM).
    • DML_LOCKS (init.ora): determines the maximum number of DML locks (one for each table modified in a transaction). You might need to increase it if you use explicit locks.
  • DDL Locks
    • Protects the definition of a schema object while an ongoing DDL operation acts on or refers to the object.
    • Users cannot explicitly request DDL locks.
    • Exclusive DDL lock: prevents other sessions from obtaining a DDL or DML lock.
    • Share DDL lock: prevents conflicting DDL operations, but allows similar DDL operations.
  • Breakable Parse Locks
    • Held by a SQL statement or PL/SQL program unit for each schema object that it references. Acquired so that the associated shared SQL area can be invalidated if a referenced object is altered or dropped.
    • A parse lock is acquired in the shared pool during the parse phase of SQL statement execution. The lock is held as long as the shared SQL area for that statement remains in the shared pool.

DML Locks
ROW LOCK (TX)
  • If a transaction obtains a lock for a row, then the transaction also acquires a lock for the table containing the row. (To prevent conflicting DDL operations).
  • Oracle stores lock information in the data block that contains the locked row.
TABLE LOCK (TM)
  • acquired when a table is modified by an I,U,D, MERGE, SELECT FOR UPDATE, or LOCK TABLE statement. TM can be held as:
  • Row Share (RS): (subshare table lock (SS)), indicates that the transaction holding the lock on the table has locked rows in the table and intends to update them. It is the least restrictive mode of table lock, offering the highest degree of concurrency for a table.
  • Row Exclusive Table Lock (RX): (subexclusive table lock (SX)), indicates that the transaction holding the lock has updated table rows or issued SELECT ... FOR UPDATE. It An allows other transactions to query, insert, update, delete, or lock rows concurrently in the same table.
  • Share Table Lock (S): allows other transactions to query the table (without using SELECT ... FOR UPDATE), but updates are allowed only if a single transaction holds the share table lock.
  • Share Row Exclusive Table Lock (SRX): (share-subexclusive table lock (SSX)). More restrictive than a share table lock. Only one transaction at a time can acquire an SSX lock on a given table. Allows other transactions to query (except for SELECT ... FOR UPDATE) but not to update the table.
  • Exclusive Table Lock (X): The most restrictive. Prohibits other transactions from performing any type of DML statement or placing any type of lock on the table.


  • System Locks: Latches, Mutexes, and Internal locks
  • Latches:
    • Serializes access to memory structures. Protect shared memory resources from corruption when accessed by multiple processes. [ (a) Concurrent modification by multiple sessions; (b) Being read by one session while being modified by another session; (c) Deallocation (aging out) of memory while being accessed. ]
    • i.e. while processing a salary update of a single employee, the database may obtain and release thousands of latches
    • Increase in latching ==> decrease in concurrency. (i.e.: excessive hard parse operations create contention for the library cache latch.)
    • V$LATCH: contains detailed latch usage statistics for each latch, including the number of times each latch was requested and waited for.
  • Mutex (Mutual exclusion object)
    • similar to a latch, but whereas a latch typically protects a group of objects, a mutex protects a single object.
  • Internal Locks
    • Dictionary cache locks, file and log mgmt locks, Tablespace and Undo segment locks)







Manual data Locks: overriding default
  • LOCK TABLE
  • SELECT FOR UPDATE clause
  • SET TRANSACTION with the READ ONLY or ISOLATION LEVEL SERIALIZABLE option


On Isolation Levels
ALTER SESSION SET ISOLATION_LEVEL = {SERIALIZABLE | READ COMMITTED | READ ONLY}

  • The ISOLATION_LEVEL parameter specifies how transactions containing database modifications are handled.
  • It is a session parameter only, NOT an initialization parameter.
  • SERIALIZABLE:
    • transaction sees only changes committed at the time the transaction—not the query—began and changes made by the transaction itself.
    • Transactions in the session use the serializable transaction isolation mode as specified in the SQL standard.
    • If a serializable transaction attempts to execute a DML statement that updates rows currently being updated by another uncommitted transaction at the start of the serializable transaction, then the DML statement fails.
    • A serializable transaction can see its own updates.
  • READ COMMITTED: (default)
    • Transactions in the session will use the default Oracle Database transaction behavior.
    • every query executed by a transaction sees only data committed before the query—not the transaction—began.
    • phantoms and fuzzy reads: because the database does not prevent other transactions from modifying data read by a query, other transactions may change data between query executions. Thus, a transaction that runs the same query twice may experience fuzzy reads and phantoms.
    • If the transaction contains DML that requires row locks held by another transaction, then the DML statement will wait until the row locks are released.


LOCK TABLE
  • explicitly locks one or more tables in a specified lock mode.
  • The lock mode determines what other locks can be placed on the table.
  • A table lock never prevents other users from querying a table, and a query never acquires a table lock
  • When a LOCK TABLE statement is issued on a view, the underlying base tables are locked
  • LOCK TABLE employees, departments IN EXCLUSIVE MODE NOWAIT;
  • MODE: [ NOWAIT | WAIT n | ]
    • NOWAIT: error if lock is not available immediately
    • WAIT n: wait up to n secs
    • <blank>: wait indefinitely to acquire the lock

what type of lock to use (check here)
  • ROW SHARE and ROW EXCLUSIVE
  • SHARE MODE
  • SHARE ROW EXCLUSIVE
  • EXCLUSIVE MODE
  • Let Oracle do the locking:
  • [ SET TRANSACTION ISOLATION LEVEL level ] or
    [ ALTER SESSION ISOLATION LEVEL level ]



















Transactions, TCL, and Isolation Levels
..later..












Autonomous transactions



Using SELECT... FOR UPDATE
  • SELECT FOR UPDATE selects the rows of the result set and locks them.
  • Enables you to base an update on the existing values in the rows, because it ensures that no other user can change those values before you update them.
  • You can also use SELECT FOR UPDATE to lock rows that you do not want to update
  • By default, SELECT FOR UPDATE waits until the requested row lock is acquired. To change this behavior, use the [ NOWAIT | WAIT | SKIP LOCKED ].
  • When SELECT FOR UPDATE is associated with an explicit cursor, the cursor is called a FOR UPDATE cursor.

set serveroutput on
declare
 my_emp_ln employees.last_name%type;
 my_emp_id number;
 my_job_id varchar2(10);
 my_sal number(8,2);
 newsal number(8,2);
 
 -- declare a FOR UPDATE cursor
 cursor c1 is
   select employee_id, last_name, job_id, salary
   from employees for update;
begin
  open c1;
  loop
    fetch c1 into my_emp_id, my_emp_ln, my_job_id, my_sal;
    If my_job_id = 'SA_REP' then
      newsal := my_sal*1.12;
      -- update only the rows locked by the cursor
      -- identified through the "WHERE CURRENT OF" clause.
      update employees
      set salary = newsal
      where current of c1;
      dbms_output.put_line('Emp '|| my_emp_ln ||
               ': salary increased from '|| my_sal ||' to '|| newsal);
    end if;
    exit when c1%notfound;
  end loop;
end;

anonymous block completed
Emp Tucker: salary increased from 10000 to 11200
Emp Bernstein: salary increased from 9500 to 10640
...