SlideShare a Scribd company logo
9
Managing Data Concurrency




   Copyright © 2009, Oracle. All rights reserved.
Objectives

After completing this lesson, you should be able to:
 • Describe the locking mechanism and how Oracle manages
     data concurrency
 • Monitor and resolve locking conflicts




9-2              Copyright © 2009, Oracle. All rights reserved.
Locks

 •      Prevent multiple sessions from changing the same data at
        the same time
 •      Are automatically obtained at the lowest possible level for
        a given statement
 •      Do not escalate




           Transaction 1                              Transaction 2
      SQL> UPDATE employees                     SQL> UPDATE employees
        2 SET salary=salary+100                   2 SET salary=salary*1.1
        3 WHERE employee_id=100;                  3 WHERE employee_id=100;




9-3                    Copyright © 2009, Oracle. All rights reserved.
Locking Mechanism

 •      High level of data concurrency:
         – Row-level locks for inserts, updates, and deletes
         – No locks required for queries
 •      Automatic queue management
 •      Locks held until the transaction ends (with the COMMIT or
        ROLLBACK operation)
      Example
      Assume that the rows for employee_id 100 and 101 reside in the same
      block:

           Transaction 1                                Transaction 2
      SQL> UPDATE employees                       SQL> UPDATE employees
        2 SET salary=salary+100                     2 SET salary=salary*1.1
        3 WHERE employee_id=100;                    3 WHERE employee_id=101;


9-4                      Copyright © 2009, Oracle. All rights reserved.
Data Concurrency


  Time:      Transaction 1               UPDATE hr.employees
                                         SET salary=salary+100
                                         WHERE employee_id=100;

             Transaction 2               UPDATE hr.employees
                                         SET salary=salary+100
                                         WHERE employee_id=101;
  09:00:00   Transaction 3               UPDATE hr.employees
                                         SET salary=salary+100
                                         WHERE employee_id=102;

             ...                         ...
             Transaction x               UPDATE hr.employees
                                         SET salary=salary+100
                                         WHERE employee_id=xxx;




9-5                Copyright © 2009, Oracle. All rights reserved.
DML Locks


      Transaction 1                           Transaction 2
      SQL> UPDATE employees                     SQL> UPDATE employees
        2 SET salary=salary*1.1                   2 SET salary=salary*1.1
        3 WHERE employee_id= 107;                 3 WHERE employee_id= 106;
      1 row updated.                            1 row updated.


Each DML transaction must acquire two locks:
 • EXCLUSIVE row lock on the row or rows being updated
 • Table lock (TM) in ROW EXCLUSIVE (RX) mode on the
    table containing the rows




9-7                    Copyright © 2009, Oracle. All rights reserved.
Enqueue Mechanism

The enqueue mechanism keeps track of:
 • Sessions waiting for locks
 • Requested lock mode
 • Order in which sessions requested the lock




9-8               Copyright © 2009, Oracle. All rights reserved.
Lock Conflicts


      Transaction 1                         Time            Transaction 2
      UPDATE employees SET    9:00:00                        UPDATE employees SET
      salary=salary+100 WHERE                                salary=salary+100 WHERE
      employee_id=100;                                       employee_id=101;
      1 row updated.                                         1 row updated.
      UPDATE employees SET          9:00:05                  SELECT sum(salary) FROM
      COMMISION_PCT=2 WHERE                                  employees;
      employee_id=101;                                       SUM(SALARY)
      Session waits enqueued due to                          -----------
      lock conflict.                                              692634
      Session still waiting!                                 Many selects, inserts, updates,
                                              16:30:00       and deletes during the last 7.5
                                                             hours, but no commits or
                                                             rollbacks!
      1 row updated.                          16:30:01       commit;
      Session continues.


9-9                            Copyright © 2009, Oracle. All rights reserved.
Possible Causes of Lock Conflicts

  •      Uncommitted changes
  •      Long-running transactions
  •      Unnecessarily high locking levels




9 - 10                 Copyright © 2009, Oracle. All rights reserved.
Detecting Lock Conflicts


 Select Blocking Sessions on the Performance page.




 Click the Session ID link to view information about the locking
 session, including the actual SQL statement.


9 - 11              Copyright © 2009, Oracle. All rights reserved.
Resolving Lock Conflicts

 To resolve a lock conflict:
  • Have the session holding the lock commit or roll back
  • Terminate the session holding the lock (in an emergency)




9 - 12             Copyright © 2009, Oracle. All rights reserved.
Resolving Lock Conflicts with SQL

 SQL statements can be used to determine the blocking session
 and kill it.


         SQL> select SID, SERIAL#, USERNAME
     1         from V$SESSION where SID in
               (select BLOCKING_SESSION from V$SESSION)


                                                 Result:




     2   SQL> alter system kill session '144,8982' immediate;




9 - 13                 Copyright © 2009, Oracle. All rights reserved.
Deadlocks



                 Transaction 1                                 Transaction 2


         UPDATE employees                             UPDATE employees
         SET salary = salary x 1.1          9:00      SET manager = 1342
         WHERE employee_id = 1000;                    WHERE employee_id = 2000;
         UPDATE employees                             UPDATE employees
         SET salary = salary x 1.1          9:15      SET manager = 1342
         WHERE employee_id = 2000;                    WHERE employee_id = 1000;
         ORA-00060:
         Deadlock detected while            9:16
         waiting for resource




9 - 14                   Copyright © 2009, Oracle. All rights reserved.
Quiz

 The lock mechanism defaults to a fine-grained, row-level
 locking mode.
  1. True
  2. False




9 - 15              Copyright © 2009, Oracle. All rights reserved.
Quiz

 When the deadlock occurs, Oracle database automatically:
 1. Waits 300 seconds before terminating both sessions
 2. Terminates one statement with an error in one session
 3. Terminates the statements with an error in both sessions
 4. Takes no action by default and leaves it to DBA




9 - 16             Copyright © 2009, Oracle. All rights reserved.
Summary

 In this lesson, you should have learned how to:
  • Describe the locking mechanism and how Oracle manages
      data concurrency
  • Monitor and resolve locking conflicts




9 - 17            Copyright © 2009, Oracle. All rights reserved.
Practice 9 Overview:
            Managing Data and Concurrency
 This practice covers the following topics:
  • Identifying locking conflicts
  • Resolving locking conflicts




9 - 18               Copyright © 2009, Oracle. All rights reserved.
Ad

More Related Content

What's hot (20)

Oracle LOB Internals and Performance Tuning
Oracle LOB Internals and Performance TuningOracle LOB Internals and Performance Tuning
Oracle LOB Internals and Performance Tuning
Tanel Poder
 
Oracle Data Masking and Subsettingのご紹介
Oracle Data Masking and Subsettingのご紹介Oracle Data Masking and Subsettingのご紹介
Oracle Data Masking and Subsettingのご紹介
オラクルエンジニア通信
 
Oracle RAC Internals - The Cache Fusion Edition
Oracle RAC Internals - The Cache Fusion EditionOracle RAC Internals - The Cache Fusion Edition
Oracle RAC Internals - The Cache Fusion Edition
Markus Michalewicz
 
What's New In MQ 9.2 on z/OS
What's New In MQ 9.2 on z/OSWhat's New In MQ 9.2 on z/OS
What's New In MQ 9.2 on z/OS
Matt Leming
 
Partitioning
PartitioningPartitioning
Partitioning
Reema Gajjar
 
Rman Presentation
Rman PresentationRman Presentation
Rman Presentation
Rick van Ek
 
Less04 database instance
Less04 database instanceLess04 database instance
Less04 database instance
Amit Bhalla
 
Oracle RAC 19c: Best Practices and Secret Internals
Oracle RAC 19c: Best Practices and Secret InternalsOracle RAC 19c: Best Practices and Secret Internals
Oracle RAC 19c: Best Practices and Secret Internals
Anil Nair
 
Fat File Systems
Fat File SystemsFat File Systems
Fat File Systems
ArthyR3
 
Oracle Database Performance Tuning Advanced Features and Best Practices for DBAs
Oracle Database Performance Tuning Advanced Features and Best Practices for DBAsOracle Database Performance Tuning Advanced Features and Best Practices for DBAs
Oracle Database Performance Tuning Advanced Features and Best Practices for DBAs
Zohar Elkayam
 
Automating Your Clone in E-Business Suite R12.2
Automating Your Clone in E-Business Suite R12.2Automating Your Clone in E-Business Suite R12.2
Automating Your Clone in E-Business Suite R12.2
Michael Brown
 
Less17 flashback tb3
Less17 flashback tb3Less17 flashback tb3
Less17 flashback tb3
Imran Ali
 
MAA Best Practices for Oracle Database 19c
MAA Best Practices for Oracle Database 19cMAA Best Practices for Oracle Database 19c
MAA Best Practices for Oracle Database 19c
Markus Michalewicz
 
Rac questions
Rac questionsRac questions
Rac questions
parvezsigan
 
Oracle RAC 12c (12.1.0.2) Operational Best Practices - A result of true colla...
Oracle RAC 12c (12.1.0.2) Operational Best Practices - A result of true colla...Oracle RAC 12c (12.1.0.2) Operational Best Practices - A result of true colla...
Oracle RAC 12c (12.1.0.2) Operational Best Practices - A result of true colla...
Markus Michalewicz
 
Oracle Enterprise Manager
Oracle Enterprise ManagerOracle Enterprise Manager
Oracle Enterprise Manager
Bob Rhubart
 
SQL Server Database Backup and Restore Plan
SQL Server Database Backup and Restore PlanSQL Server Database Backup and Restore Plan
SQL Server Database Backup and Restore Plan
Hamid J. Fard
 
Oracle Database統合のベスト・プラクティス
Oracle Database統合のベスト・プラクティスOracle Database統合のベスト・プラクティス
Oracle Database統合のベスト・プラクティス
オラクルエンジニア通信
 
User, roles and privileges
User, roles and privilegesUser, roles and privileges
User, roles and privileges
Yogiji Creations
 
What to Expect From Oracle database 19c
What to Expect From Oracle database 19cWhat to Expect From Oracle database 19c
What to Expect From Oracle database 19c
Maria Colgan
 
Oracle LOB Internals and Performance Tuning
Oracle LOB Internals and Performance TuningOracle LOB Internals and Performance Tuning
Oracle LOB Internals and Performance Tuning
Tanel Poder
 
Oracle RAC Internals - The Cache Fusion Edition
Oracle RAC Internals - The Cache Fusion EditionOracle RAC Internals - The Cache Fusion Edition
Oracle RAC Internals - The Cache Fusion Edition
Markus Michalewicz
 
What's New In MQ 9.2 on z/OS
What's New In MQ 9.2 on z/OSWhat's New In MQ 9.2 on z/OS
What's New In MQ 9.2 on z/OS
Matt Leming
 
Rman Presentation
Rman PresentationRman Presentation
Rman Presentation
Rick van Ek
 
Less04 database instance
Less04 database instanceLess04 database instance
Less04 database instance
Amit Bhalla
 
Oracle RAC 19c: Best Practices and Secret Internals
Oracle RAC 19c: Best Practices and Secret InternalsOracle RAC 19c: Best Practices and Secret Internals
Oracle RAC 19c: Best Practices and Secret Internals
Anil Nair
 
Fat File Systems
Fat File SystemsFat File Systems
Fat File Systems
ArthyR3
 
Oracle Database Performance Tuning Advanced Features and Best Practices for DBAs
Oracle Database Performance Tuning Advanced Features and Best Practices for DBAsOracle Database Performance Tuning Advanced Features and Best Practices for DBAs
Oracle Database Performance Tuning Advanced Features and Best Practices for DBAs
Zohar Elkayam
 
Automating Your Clone in E-Business Suite R12.2
Automating Your Clone in E-Business Suite R12.2Automating Your Clone in E-Business Suite R12.2
Automating Your Clone in E-Business Suite R12.2
Michael Brown
 
Less17 flashback tb3
Less17 flashback tb3Less17 flashback tb3
Less17 flashback tb3
Imran Ali
 
MAA Best Practices for Oracle Database 19c
MAA Best Practices for Oracle Database 19cMAA Best Practices for Oracle Database 19c
MAA Best Practices for Oracle Database 19c
Markus Michalewicz
 
Oracle RAC 12c (12.1.0.2) Operational Best Practices - A result of true colla...
Oracle RAC 12c (12.1.0.2) Operational Best Practices - A result of true colla...Oracle RAC 12c (12.1.0.2) Operational Best Practices - A result of true colla...
Oracle RAC 12c (12.1.0.2) Operational Best Practices - A result of true colla...
Markus Michalewicz
 
Oracle Enterprise Manager
Oracle Enterprise ManagerOracle Enterprise Manager
Oracle Enterprise Manager
Bob Rhubart
 
SQL Server Database Backup and Restore Plan
SQL Server Database Backup and Restore PlanSQL Server Database Backup and Restore Plan
SQL Server Database Backup and Restore Plan
Hamid J. Fard
 
User, roles and privileges
User, roles and privilegesUser, roles and privileges
User, roles and privileges
Yogiji Creations
 
What to Expect From Oracle database 19c
What to Expect From Oracle database 19cWhat to Expect From Oracle database 19c
What to Expect From Oracle database 19c
Maria Colgan
 

Viewers also liked (20)

Less08 users
Less08 usersLess08 users
Less08 users
Amit Bhalla
 
Less07 storage
Less07 storageLess07 storage
Less07 storage
Amit Bhalla
 
Less17 moving data
Less17 moving dataLess17 moving data
Less17 moving data
Amit Bhalla
 
Less09 Data
Less09 DataLess09 Data
Less09 Data
vivaankumar
 
Less11 auditing
Less11 auditingLess11 auditing
Less11 auditing
Amit Bhalla
 
Less18 moving data
Less18 moving dataLess18 moving data
Less18 moving data
Imran Ali
 
Less13 performance
Less13 performanceLess13 performance
Less13 performance
Amit Bhalla
 
Less06 users
Less06 usersLess06 users
Less06 users
Imran Ali
 
Less05 asm instance
Less05 asm instanceLess05 asm instance
Less05 asm instance
Amit Bhalla
 
Less08 managing data and concurrency
Less08 managing data and concurrencyLess08 managing data and concurrency
Less08 managing data and concurrency
Imran Ali
 
Less10 Undo
Less10 UndoLess10 Undo
Less10 Undo
vivaankumar
 
Less18 support
Less18 supportLess18 support
Less18 support
Amit Bhalla
 
Less02 installation
Less02 installationLess02 installation
Less02 installation
Amit Bhalla
 
Less03 db dbca
Less03 db dbcaLess03 db dbca
Less03 db dbca
Amit Bhalla
 
Oracle 12c Automatic Dynamic Sampling
Oracle 12c Automatic Dynamic SamplingOracle 12c Automatic Dynamic Sampling
Oracle 12c Automatic Dynamic Sampling
Igor Usoltsev
 
Less06 Storage
Less06 StorageLess06 Storage
Less06 Storage
vivaankumar
 
Undo internals paper
Undo internals paperUndo internals paper
Undo internals paper
oracle documents
 
Oracle 10g Forms Lesson 9
Oracle 10g Forms Lesson 9Oracle 10g Forms Lesson 9
Oracle 10g Forms Lesson 9
KAMA3
 
Indexes and Indexing in Oracle 12c
Indexes and Indexing in Oracle 12cIndexes and Indexing in Oracle 12c
Indexes and Indexing in Oracle 12c
Oren Nakdimon
 
Oracle 12c RAC On your laptop Step by Step Implementation Guide 1.0
Oracle 12c RAC On your laptop Step by Step Implementation Guide 1.0Oracle 12c RAC On your laptop Step by Step Implementation Guide 1.0
Oracle 12c RAC On your laptop Step by Step Implementation Guide 1.0
Yury Velikanov
 
Less17 moving data
Less17 moving dataLess17 moving data
Less17 moving data
Amit Bhalla
 
Less18 moving data
Less18 moving dataLess18 moving data
Less18 moving data
Imran Ali
 
Less13 performance
Less13 performanceLess13 performance
Less13 performance
Amit Bhalla
 
Less06 users
Less06 usersLess06 users
Less06 users
Imran Ali
 
Less05 asm instance
Less05 asm instanceLess05 asm instance
Less05 asm instance
Amit Bhalla
 
Less08 managing data and concurrency
Less08 managing data and concurrencyLess08 managing data and concurrency
Less08 managing data and concurrency
Imran Ali
 
Less02 installation
Less02 installationLess02 installation
Less02 installation
Amit Bhalla
 
Oracle 12c Automatic Dynamic Sampling
Oracle 12c Automatic Dynamic SamplingOracle 12c Automatic Dynamic Sampling
Oracle 12c Automatic Dynamic Sampling
Igor Usoltsev
 
Oracle 10g Forms Lesson 9
Oracle 10g Forms Lesson 9Oracle 10g Forms Lesson 9
Oracle 10g Forms Lesson 9
KAMA3
 
Indexes and Indexing in Oracle 12c
Indexes and Indexing in Oracle 12cIndexes and Indexing in Oracle 12c
Indexes and Indexing in Oracle 12c
Oren Nakdimon
 
Oracle 12c RAC On your laptop Step by Step Implementation Guide 1.0
Oracle 12c RAC On your laptop Step by Step Implementation Guide 1.0Oracle 12c RAC On your laptop Step by Step Implementation Guide 1.0
Oracle 12c RAC On your laptop Step by Step Implementation Guide 1.0
Yury Velikanov
 
Ad

Similar to Less09 locking (20)

Database concurrency and transactions - Tal Olier
Database concurrency and transactions - Tal OlierDatabase concurrency and transactions - Tal Olier
Database concurrency and transactions - Tal Olier
sqlserver.co.il
 
Welcome to the nightmare of locking, blocking and isolation levels!
Welcome to the nightmare of locking, blocking and isolation levels!Welcome to the nightmare of locking, blocking and isolation levels!
Welcome to the nightmare of locking, blocking and isolation levels!
Boris Hristov
 
Useful PL/SQL Supplied Packages
Useful PL/SQL Supplied PackagesUseful PL/SQL Supplied Packages
Useful PL/SQL Supplied Packages
Maria Colgan
 
你所不知道的Oracle后台进程Smon功能
你所不知道的Oracle后台进程Smon功能你所不知道的Oracle后台进程Smon功能
你所不知道的Oracle后台进程Smon功能
maclean liu
 
Oracle Connection Manager
Oracle Connection ManagerOracle Connection Manager
Oracle Connection Manager
Viaggio Italia
 
Long live to CMAN!
Long live to CMAN!Long live to CMAN!
Long live to CMAN!
Ludovico Caldara
 
Les 10 fl1
Les 10 fl1Les 10 fl1
Les 10 fl1
Femi Adeyemi
 
Enterprise managerclodcontrolinstallconfiguration emc12c
Enterprise managerclodcontrolinstallconfiguration emc12cEnterprise managerclodcontrolinstallconfiguration emc12c
Enterprise managerclodcontrolinstallconfiguration emc12c
Rakesh Gujjarlapudi
 
Pl sql-ch2
Pl sql-ch2Pl sql-ch2
Pl sql-ch2
Mukesh Tekwani
 
10 Creating Triggers
10 Creating Triggers10 Creating Triggers
10 Creating Triggers
rehaniltifat
 
Performance tuning a quick intoduction
Performance tuning   a quick intoductionPerformance tuning   a quick intoduction
Performance tuning a quick intoduction
Riyaj Shamsudeen
 
oracle pl-sql lec 7 oracle pl-sql lec 7 plsql Lec07.ppt
oracle pl-sql lec 7 oracle pl-sql lec 7 plsql Lec07.pptoracle pl-sql lec 7 oracle pl-sql lec 7 plsql Lec07.ppt
oracle pl-sql lec 7 oracle pl-sql lec 7 plsql Lec07.ppt
ka77931067
 
Replication Tips & Tricks
Replication Tips & TricksReplication Tips & Tricks
Replication Tips & Tricks
Mats Kindahl
 
Oracle database locking mechanism demystified (AOUG)
Oracle database locking mechanism demystified (AOUG)Oracle database locking mechanism demystified (AOUG)
Oracle database locking mechanism demystified (AOUG)
Pini Dibask
 
plsql les10
 plsql les10 plsql les10
plsql les10
sasa_eldoby
 
OTN TOUR 2016 - DBA Commands and Concepts That Every Developer Should Know
OTN TOUR 2016 - DBA Commands and Concepts That Every Developer Should KnowOTN TOUR 2016 - DBA Commands and Concepts That Every Developer Should Know
OTN TOUR 2016 - DBA Commands and Concepts That Every Developer Should Know
Alex Zaballa
 
OTN TOUR 2016 - DBA Commands and Concepts That Every Developer Should Know
OTN TOUR 2016 - DBA Commands and Concepts That Every Developer Should KnowOTN TOUR 2016 - DBA Commands and Concepts That Every Developer Should Know
OTN TOUR 2016 - DBA Commands and Concepts That Every Developer Should Know
Alex Zaballa
 
Sherlock holmes for dba’s
Sherlock holmes for dba’sSherlock holmes for dba’s
Sherlock holmes for dba’s
Kellyn Pot'Vin-Gorman
 
Pini Dibask - Oracle Database Locking Mechanism Demystified (Presentation)
Pini Dibask - Oracle Database Locking Mechanism Demystified (Presentation)Pini Dibask - Oracle Database Locking Mechanism Demystified (Presentation)
Pini Dibask - Oracle Database Locking Mechanism Demystified (Presentation)
Pini Dibask
 
DOAG - Oracle Database Locking Mechanism Demystified
DOAG - Oracle Database Locking Mechanism Demystified DOAG - Oracle Database Locking Mechanism Demystified
DOAG - Oracle Database Locking Mechanism Demystified
Pini Dibask
 
Database concurrency and transactions - Tal Olier
Database concurrency and transactions - Tal OlierDatabase concurrency and transactions - Tal Olier
Database concurrency and transactions - Tal Olier
sqlserver.co.il
 
Welcome to the nightmare of locking, blocking and isolation levels!
Welcome to the nightmare of locking, blocking and isolation levels!Welcome to the nightmare of locking, blocking and isolation levels!
Welcome to the nightmare of locking, blocking and isolation levels!
Boris Hristov
 
Useful PL/SQL Supplied Packages
Useful PL/SQL Supplied PackagesUseful PL/SQL Supplied Packages
Useful PL/SQL Supplied Packages
Maria Colgan
 
你所不知道的Oracle后台进程Smon功能
你所不知道的Oracle后台进程Smon功能你所不知道的Oracle后台进程Smon功能
你所不知道的Oracle后台进程Smon功能
maclean liu
 
Oracle Connection Manager
Oracle Connection ManagerOracle Connection Manager
Oracle Connection Manager
Viaggio Italia
 
Enterprise managerclodcontrolinstallconfiguration emc12c
Enterprise managerclodcontrolinstallconfiguration emc12cEnterprise managerclodcontrolinstallconfiguration emc12c
Enterprise managerclodcontrolinstallconfiguration emc12c
Rakesh Gujjarlapudi
 
10 Creating Triggers
10 Creating Triggers10 Creating Triggers
10 Creating Triggers
rehaniltifat
 
Performance tuning a quick intoduction
Performance tuning   a quick intoductionPerformance tuning   a quick intoduction
Performance tuning a quick intoduction
Riyaj Shamsudeen
 
oracle pl-sql lec 7 oracle pl-sql lec 7 plsql Lec07.ppt
oracle pl-sql lec 7 oracle pl-sql lec 7 plsql Lec07.pptoracle pl-sql lec 7 oracle pl-sql lec 7 plsql Lec07.ppt
oracle pl-sql lec 7 oracle pl-sql lec 7 plsql Lec07.ppt
ka77931067
 
Replication Tips & Tricks
Replication Tips & TricksReplication Tips & Tricks
Replication Tips & Tricks
Mats Kindahl
 
Oracle database locking mechanism demystified (AOUG)
Oracle database locking mechanism demystified (AOUG)Oracle database locking mechanism demystified (AOUG)
Oracle database locking mechanism demystified (AOUG)
Pini Dibask
 
OTN TOUR 2016 - DBA Commands and Concepts That Every Developer Should Know
OTN TOUR 2016 - DBA Commands and Concepts That Every Developer Should KnowOTN TOUR 2016 - DBA Commands and Concepts That Every Developer Should Know
OTN TOUR 2016 - DBA Commands and Concepts That Every Developer Should Know
Alex Zaballa
 
OTN TOUR 2016 - DBA Commands and Concepts That Every Developer Should Know
OTN TOUR 2016 - DBA Commands and Concepts That Every Developer Should KnowOTN TOUR 2016 - DBA Commands and Concepts That Every Developer Should Know
OTN TOUR 2016 - DBA Commands and Concepts That Every Developer Should Know
Alex Zaballa
 
Pini Dibask - Oracle Database Locking Mechanism Demystified (Presentation)
Pini Dibask - Oracle Database Locking Mechanism Demystified (Presentation)Pini Dibask - Oracle Database Locking Mechanism Demystified (Presentation)
Pini Dibask - Oracle Database Locking Mechanism Demystified (Presentation)
Pini Dibask
 
DOAG - Oracle Database Locking Mechanism Demystified
DOAG - Oracle Database Locking Mechanism Demystified DOAG - Oracle Database Locking Mechanism Demystified
DOAG - Oracle Database Locking Mechanism Demystified
Pini Dibask
 
Ad

Less09 locking

  • 1. 9 Managing Data Concurrency Copyright © 2009, Oracle. All rights reserved.
  • 2. Objectives After completing this lesson, you should be able to: • Describe the locking mechanism and how Oracle manages data concurrency • Monitor and resolve locking conflicts 9-2 Copyright © 2009, Oracle. All rights reserved.
  • 3. Locks • Prevent multiple sessions from changing the same data at the same time • Are automatically obtained at the lowest possible level for a given statement • Do not escalate Transaction 1 Transaction 2 SQL> UPDATE employees SQL> UPDATE employees 2 SET salary=salary+100 2 SET salary=salary*1.1 3 WHERE employee_id=100; 3 WHERE employee_id=100; 9-3 Copyright © 2009, Oracle. All rights reserved.
  • 4. Locking Mechanism • High level of data concurrency: – Row-level locks for inserts, updates, and deletes – No locks required for queries • Automatic queue management • Locks held until the transaction ends (with the COMMIT or ROLLBACK operation) Example Assume that the rows for employee_id 100 and 101 reside in the same block: Transaction 1 Transaction 2 SQL> UPDATE employees SQL> UPDATE employees 2 SET salary=salary+100 2 SET salary=salary*1.1 3 WHERE employee_id=100; 3 WHERE employee_id=101; 9-4 Copyright © 2009, Oracle. All rights reserved.
  • 5. Data Concurrency Time: Transaction 1 UPDATE hr.employees SET salary=salary+100 WHERE employee_id=100; Transaction 2 UPDATE hr.employees SET salary=salary+100 WHERE employee_id=101; 09:00:00 Transaction 3 UPDATE hr.employees SET salary=salary+100 WHERE employee_id=102; ... ... Transaction x UPDATE hr.employees SET salary=salary+100 WHERE employee_id=xxx; 9-5 Copyright © 2009, Oracle. All rights reserved.
  • 6. DML Locks Transaction 1 Transaction 2 SQL> UPDATE employees SQL> UPDATE employees 2 SET salary=salary*1.1 2 SET salary=salary*1.1 3 WHERE employee_id= 107; 3 WHERE employee_id= 106; 1 row updated. 1 row updated. Each DML transaction must acquire two locks: • EXCLUSIVE row lock on the row or rows being updated • Table lock (TM) in ROW EXCLUSIVE (RX) mode on the table containing the rows 9-7 Copyright © 2009, Oracle. All rights reserved.
  • 7. Enqueue Mechanism The enqueue mechanism keeps track of: • Sessions waiting for locks • Requested lock mode • Order in which sessions requested the lock 9-8 Copyright © 2009, Oracle. All rights reserved.
  • 8. Lock Conflicts Transaction 1 Time Transaction 2 UPDATE employees SET 9:00:00 UPDATE employees SET salary=salary+100 WHERE salary=salary+100 WHERE employee_id=100; employee_id=101; 1 row updated. 1 row updated. UPDATE employees SET 9:00:05 SELECT sum(salary) FROM COMMISION_PCT=2 WHERE employees; employee_id=101; SUM(SALARY) Session waits enqueued due to ----------- lock conflict. 692634 Session still waiting! Many selects, inserts, updates, 16:30:00 and deletes during the last 7.5 hours, but no commits or rollbacks! 1 row updated. 16:30:01 commit; Session continues. 9-9 Copyright © 2009, Oracle. All rights reserved.
  • 9. Possible Causes of Lock Conflicts • Uncommitted changes • Long-running transactions • Unnecessarily high locking levels 9 - 10 Copyright © 2009, Oracle. All rights reserved.
  • 10. Detecting Lock Conflicts Select Blocking Sessions on the Performance page. Click the Session ID link to view information about the locking session, including the actual SQL statement. 9 - 11 Copyright © 2009, Oracle. All rights reserved.
  • 11. Resolving Lock Conflicts To resolve a lock conflict: • Have the session holding the lock commit or roll back • Terminate the session holding the lock (in an emergency) 9 - 12 Copyright © 2009, Oracle. All rights reserved.
  • 12. Resolving Lock Conflicts with SQL SQL statements can be used to determine the blocking session and kill it. SQL> select SID, SERIAL#, USERNAME 1 from V$SESSION where SID in (select BLOCKING_SESSION from V$SESSION) Result: 2 SQL> alter system kill session '144,8982' immediate; 9 - 13 Copyright © 2009, Oracle. All rights reserved.
  • 13. Deadlocks Transaction 1 Transaction 2 UPDATE employees UPDATE employees SET salary = salary x 1.1 9:00 SET manager = 1342 WHERE employee_id = 1000; WHERE employee_id = 2000; UPDATE employees UPDATE employees SET salary = salary x 1.1 9:15 SET manager = 1342 WHERE employee_id = 2000; WHERE employee_id = 1000; ORA-00060: Deadlock detected while 9:16 waiting for resource 9 - 14 Copyright © 2009, Oracle. All rights reserved.
  • 14. Quiz The lock mechanism defaults to a fine-grained, row-level locking mode. 1. True 2. False 9 - 15 Copyright © 2009, Oracle. All rights reserved.
  • 15. Quiz When the deadlock occurs, Oracle database automatically: 1. Waits 300 seconds before terminating both sessions 2. Terminates one statement with an error in one session 3. Terminates the statements with an error in both sessions 4. Takes no action by default and leaves it to DBA 9 - 16 Copyright © 2009, Oracle. All rights reserved.
  • 16. Summary In this lesson, you should have learned how to: • Describe the locking mechanism and how Oracle manages data concurrency • Monitor and resolve locking conflicts 9 - 17 Copyright © 2009, Oracle. All rights reserved.
  • 17. Practice 9 Overview: Managing Data and Concurrency This practice covers the following topics: • Identifying locking conflicts • Resolving locking conflicts 9 - 18 Copyright © 2009, Oracle. All rights reserved.

Editor's Notes

  • #3: Oracle Database 11 g : Administration Workshop I 9 -
  • #4: Oracle Database 11 g : Administration Workshop I 9 - Locks Before the database allows a session to modify data, the session must first lock the data that is being modified. A lock gives the session exclusive control over the data so that no other transaction can modify the locked data until the lock is released. Transactions can lock individual rows of data, multiple rows, or even entire tables. Oracle Database supports both manual and automatic locking. Automatically acquired locks always choose the lowest possible level of locking to minimize potential conflicts with other transactions. Note: There are many types of locks used by the Oracle instance to maintain internal consistency. In this course, we will be concentrating only locking used to protect rows and tables.
  • #5: Oracle Database 11 g : Administration Workshop I 9 - Locking Mechanism The locking mechanism is designed to provide the maximum possible degree of data concurrency within the database. Transactions that modify data acquire row-level locks rather than block-level or table-level locks. Modifications to objects (such as table moves) obtain object-level locks rather than whole database or schema locks. Data queries do not require a lock, and a query succeeds even if someone has locked the data (always showing the original, prelock value reconstructed from undo information). When multiple transactions need to lock the same resource, the first transaction to request the lock obtains it. Other transactions wait until the first transaction completes. The queue mechanism is automatic and requires no administrator interaction. All locks are released as transactions are completed (that is, when a COMMIT or ROLLBACK is issued). In the case of a failed transaction, the same background process that automatically rolls back any changes from the failed transaction releases all locks held by that transaction.
  • #6: Oracle Database 11 g : Administration Workshop I 9 - Data Concurrency The lock mechanism defaults to a fine-grained, row-level locking mode. Different transactions can be updating different rows within the same table without interfering with one another. Although the default model is to lock at the row level, Oracle Database supports manual locking at higher levels if needed: SQL> LOCK TABLE employees IN EXCLUSIVE MODE; Table(s) Locked. With the preceding statement, any other transaction that tries to update a row in the locked table must wait until the transaction that issued the lock request completes. EXCLUSIVE is the strictest lock mode. The following are the other lock modes: ROW SHARE : Permits concurrent access to the locked table but prohibits sessions from locking the entire table for exclusive access ROW EXCLUSIVE : Is the same as ROW SHARE , but also prohibits locking in SHARE mode. The ROW EXCLUSIVE locks are automatically obtained when updating, inserting, or deleting data. ROW EXCLUSIVE locks allow multiple readers and one writer. SHARE : Permits concurrent queries but prohibits updates to the locked table. A SHARE lock is required (and automatically requested) to create an index on a table. However, online index creation requires a ROW SHARE lock that is used when building the index.
  • #7: Data Concurrency (continued) Share locks allow multiple readers and no writers. Share locks are also used transparently when deleting or updating rows in a parent table that has a child table with foreign key constraints on the parent. SHARE ROW EXCLUSIVE : Is used to query a whole table and to allow others to query rows in the table, but prohibits others from locking the table in SHARE mode or updating rows EXCLUSIVE : Permits queries on the locked table but prohibits any other activity on it. An EXCLUSIVE lock is required to drop a table. Like any request for a lock, manual lock statements wait until all sessions that either already have locks or have previously requested locks release their locks. The LOCK command accepts a special argument that controls the waiting behavior NOWAIT . NOWAIT returns control to you immediately if the specified table is already locked by another session: SQL> LOCK TABLE hr.employees IN SHARE MODE NOWAIT; LOCK TABLE hr.employees IN SHARE MODE NOWAIT * ERROR at line 1: ORA-00054: resource busy and acquire with NOWAIT specified It is usually not necessary to manually lock objects. The automatic locking mechanism provides the data concurrency needed for most applications. Oracle recommends that you avoid using manual locks, especially when developing applications. Severe performance issues often occur from unnecessarily high locking levels.
  • #8: DML Locks Each DML transaction obtains two locks: An EXCLUSIVE row lock on the row or rows being updated A table lock (TM) in ROW EXCLUSIVE (RX) mode on the table being updated. This prevents another session from locking the whole table (possibly to drop or truncate it) while the change is being made. This mode is also called a subexclusive table lock (SX) . A ROW EXCLUSIVE lock on the table prevents DDL commands from changing the dictionary metadata in the middle of an uncommited transaction. This preserves dictionary integrity and read consistency across the life of a transaction.
  • #9: Oracle Database 11 g : Administration Workshop I 9 - Enqueue Mechanism Requests for locks are automatically queued. As soon as the transaction holding a lock is completed, the next session in line receives the lock. The enqueue mechanism tracks the order in which locks are requested and the requested lock mode. Sessions that already hold a lock can request that the lock be converted without having to go to the end of the queue. For example, suppose a session holds a SHARE lock on a table. The session can request that the SHARE lock be converted to an EXCLUSIVE lock. If no other transaction already has an EXCLUSIVE or SHARE lock on the table, the session holding the SHARE lock is granted an EXCLUSIVE lock without having to wait in the queue again. Note: There are two categories of waiters for enqueues: those waiting without shared ownership and those with shared ownership that do not choose to escalate the lock level. Waiters in the second category are known as converters , which are always given priority over normal waiters even if they have been waiting less time.
  • #10: Oracle Database 11 g : Administration Workshop I 9 - Lock Conflicts Lock conflicts occur often but are usually resolved through time and the enqueue mechanism. In certain rare cases, a lock conflict may require administrator intervention. In the case in the slide, transaction 2 obtains a lock on a single row at 9:00:00 and neglects to commit, leaving the lock in place. Transaction 1 attempts to update the entire table, requiring a lock on all rows, at 9:00:05. Transaction 1 is blocked by transaction 2 until transaction 2 commits at 16:30:01. A user attempting to perform transaction 1 would almost certainly contact the administrator for help in this case, and the DBA would have to detect and resolve the conflict.
  • #11: Oracle Database 11 g : Administration Workshop I 9 - Possible Causes of Lock Conflicts The most common cause of lock conflicts is an uncommitted change, but there are a few other possible causes: Long-running transactions: Many applications use batch processing to perform bulk updates. These batch jobs are usually scheduled for times of low or no user activity, but in some cases, they may not have finished or may take too long to run during the low activity period. Lock conflicts are common when transaction and batch processing are being performed simultaneously. Unnecessarily high locking levels: Not all databases support row-level locking (Oracle added support for row-level locks in 1988 with release 6). Some databases still lock at the page or table level. Developers writing applications that are intended to run on many different databases often write their applications with artificially high locking levels so that Oracle Database behaves similarly to these less capable database systems. Developers who are new to Oracle also sometimes unnecessarily code in higher locking levels than are required by Oracle Database.
  • #12: Oracle Database 11 g : Administration Workshop I 9 - Detecting Lock Conflicts Use the Blocking Sessions page in Enterprise Manager to locate lock conflicts. Conflicting lock requests are shown in hierarchical layout, showing the session holding the lock at the top and, below that, any sessions that are enqueued for the lock. For each session involved in the conflict, you are given the username, session ID, and number of seconds for which the session has been waiting. Drill down to the session ID to see actual SQL statements that are currently being executed or requested by the session. The Automatic Database Diagnostic Monitor (ADDM) also automatically detects lock conflicts and can advise you on inefficient locking trends.
  • #13: Oracle Database 11 g : Administration Workshop I 9 - Resolving Lock Conflicts To resolve a lock conflict, the session holding the lock must release it. The best way to have the session release the lock is to contact the user and ask that the transaction be completed. In an emergency, it is possible for the administrator to terminate the session holding the lock by clicking the Kill Session button. Remember that when a session is killed, all work within the current transaction is lost (rolled back). A user whose session is killed must log in again and redo all work since the killed session’s last commit. Users whose sessions have been killed receive the following error the next time they try to issue a SQL statement: ORA-03135: connection lost contact Note: The PMON session sniper can automatically kill sessions due to idle timeout, and this can be done by using profiles or Resource Manager.
  • #14: Oracle Database 11 g : Administration Workshop I 9 - Resolving Lock Conflicts Using SQL Session manipulation, like most other tasks in Enterprise Manager, can also be done by issuing SQL statements. The V$SESSION table contains details of all connected sessions. The value in BLOCKING_SESSION is the session ID of the session that is blocking. If you query for SID and SERIAL# (where SID matches a blocking session ID), you have the information needed to perform the kill session operation. Note: Database Resource Manager can be used to automatically log out sessions that block others and are idle.
  • #15: Oracle Database 11 g : Administration Workshop I 9 - Deadlocks A deadlock is a special example of a lock conflict. Deadlocks arise when two or more sessions wait for data that has been locked by the other. Because each is waiting for the other, neither can complete their transaction to resolve the conflict. Oracle Database automatically detects deadlocks and terminates the statement with an error. The proper response to that error is either commit or rollback, which releases any other locks in that session so that the other session can continue its transaction. In the example in the slide, transaction 1 must either commit or roll back in response to the deadlock detected error. If it commits, it must resubmit the second update to complete its transaction. If it performs a rollback, it must resubmit both statements to complete its transaction.
  • #16: Answer: 1
  • #17: Answer: 2
  • #18: Oracle Database 11 g : Administration Workshop I 9 -
  • #19: Oracle Database 11 g : Administration Workshop I 9 -