- 浏览: 70777 次
- 性别:
- 来自: 杭州
文章分类
最新评论
|
|||||||||||||||||||||||||||||||||||||||||||||||||||||||
Row-Level Locking
Table-Level Locking
Releasing Locks
Modes of Locking
Exclusive Locks
Share Locks
Description of each Lock Mode
Row Share Table Locks (RS)
Permitted Operations:
Prohibited Operations:
When to Lock with ROW SHARE Mode:
Example
Row Exclusive Table Locks (RX)
Permitted Operations:
Prohibited Operations:
When to Lock with ROW EXCLUSIVE Mode:
Example
Share Table Locks (S)
Permitted Operations:
Prohibited Operations:
When to Lock with SHARE Mode
Example 1
Example 2
Exclusive Table Locks (X)
Permitted Operations:
Prohibited Operations:
Be careful to use an EXCLUSIVE lock!
Example
|
Session 1 |
Session 2 |
Time |
update emp set |
update emp set |
A |
In the example, no problem exists at time point A, as each transaction has a row lock on the row it attempts to update. Each transaction proceeds without being terminated. However, each tries next to update the row currently held by the other transaction. Therefore, a deadlock results at time point B, because neither transaction can obtain the resource it needs to proceed or terminate. It is a deadlock because no matter how long each transaction waits, the conflicting locks are held.
Automatic Deadlock Detection
Oracle performs automatic deadlock detection for enqueue locking deadlocks. Deadlock detection is initiated whenever an enqueue wait times out, if the resource type required is regarded as deadlock sensitive, and if the lock state for the resource has not changed. If any session that is holding a lock on the required resource in an incompatible mode is waiting directly or indirectly for a resource that is held by the current session in an incompatible mode, then a deadlock exists.
If a deadlock is detected, the session that was unlucky enough to find it aborts its lock request and rolls back its current statement in order to break the deadlock. Note that this is a rollback of the current statement only, not necessarily the entire transaction. Oracle places an implicit savepoint at the beginning of each statement, called the default savepoint, and it is to this savepoint that the transaction is rolled back in the first case. This is enough to resolve the technical deadlock. However, the interacting sessions may well remain blocked.
ORA-60 error in ALERT.LOG
An ORA-60 error is returned to the session that found the deadlock, and if this exception is not handled, then depending on the rules of the application development tool, the entire transaction is normally rolled back, and a deadlock state dump written to the user dump destination directory. This, of course, resolves the deadlock entirely. The enqueue deadlocks statistic in V$SYSSTAT records the number of times that an enqueue deadlock has been detected.
select name, value
from v$sysstat
where name = 'enqueue deadlocks';
NAME VALUE
------------------------------------------------------------ ----------
enqueue deadlocks 1
How to avoid Deadlocks
Application developers can eliminate all risk of enqueue deadlocks by ensuring that transactions requiring multiple resources always lock them in the same order. However, in complex applications, this is easier said than done, particularly if an ad hoc query tool is used. To be safe, you should adopt a strict locking order, but you must also handle the ORA-60 exception appropriately. In some cases it may be sufficient to pause for three seconds, and then retry the statement. However, in general, it is safest to roll back the transaction entirely, before pausing and retrying.
Referential Integrity Locks (RI Locks)
With the introduction of automated referential integrity (RI) came a whole new suite of locking problems. What seems at first to be a DBA's blessing can turn out to be an absolute nightmare when the DBA doesn't fully understand the implications of this feature. Why is this so?
RI constraints are validated by the database via a simple SELECT from the dependent (parent) table in question-very simple, very straightforward. If a row is deleted or a primary key is modified within the parent table, all associated child tables need to be scanned to make sure no orphaned records will result. If a row is inserted or the foreign key is modified, the parent table is scanned to ensure that the new foreign key value(s) is valid. If a DELETE CASCADE clause is included, all associated child table records are deleted. Problems begin to arise when we look at how the referential integrity is enforced.
Oracle assumes the existence of an index over every foreign key within a table. This assumption is valid for a primary key constraint or even a unique key constraint but a little presumptuous for every foreign key.
Index or no Index on Foreign Key's ?
If an index exists on the foreign key column of the child table, no DML locks, other than a lock over the rows being modified, are required.
If the index is not created, a share lock is taken out on the child table for the duration of the transaction.
The referential integrity validation could take several minutes or even hours to resolve. The share lock over the child table will allow other users to simultaneously read from the table, while restricting certain types of modification. The share lock over the table can actually block other normal, everyday modification of other rows in that table.
You can use the script: show_missing_fk_index.sql to check unindexed foreign keys:
SQL> start show_missing_fk_index.sql
Please enter Owner Name and Table Name. Wildcards allowed (DEFAULT: %)
eg.: SCOTT, S% OR %
eg.: EMP, E% OR %
Owner <%>: SCOTT
Tables <%>:
Unindexed Foreign Keys owned by Owner: SCOTT
Table Name 1. Column Constraint Name
------------------------ ------------------------ ---------------
EMP DEPTNO FK_EMP_DEPT
What is so dangerous about a Cascading Delete ?
Oracle allows to enhance a referential integrity definition to included cascading deletion. If a row is deleted from a parent table, all of the associated children will be automatically purged. This behavior obviously will affect an application's locking strategy, again circumnavigating normal object locking, removing control from the programmer.
What is so dangerous about a cascading delete? A deleted child table might, in turn, have its own child tables. Even worse, the child tables could have table-level triggers that begin to fire. What starts out as a simple, single-record delete from a harmless table could turn into an uncontrollable torrent of cascading deletes and stored database triggers.
DELETE CASCADE constraints can be found with the following script:
SQL> SELECT OWNER,
CONSTRAINT_NAME,
CONSTRAINT_TYPE,
TABLE_NAME,
DELETE_RULE
FROM USER_CONSTRAINTS
WHERE DELETE_RULE IS NOT NULL;CONSTRAINT_NAME C TABLE_NAME DELETE_RU
------------------------------ - ----------------- ---------
FK_EMP_DEPT R EMP CASCADE
Blocking Locks
Oracle resolves true enqueue deadlocks so quickly that overall system activity is scarcely affected. However, blocking locks can bring application processing to a standstill. For example, if a long-running transaction takes a shared mode lock on a key application table, then all updates to that table must wait.
There are numerous ways of attempting to diagnose blocking lock situations, normally with the intention of killing the offending session.
Blocking locks are almost always TX (transaction) locks or TM (table) locks . When a session waits on a TX lock, it is waiting for that transaction to either commit or roll back. The reason for waiting is that the transaction has modified a data block, and the waiting session needs to modify the same part of that block. In such cases, the row wait columns of V$SESSION can be useful in identifying the database object, file, and block numbers concerned, and even the row number in the case of row locks. V$LOCKED_OBJECT can then be used to obtain session information for the sessions holding DML locks on the crucial database object. This is based on the fact that sessions with blocking TX enqueue locks always hold a DML lock as well, unless DML locks have been disabled.
It may not be adequate, however, to identify a single blocking session, because it may, in turn, be blocked by another session. To address this requirement, Oracle's UTLLOCKT.SQL script gives a tree-structured report showing the relationship between blocking and waiting sessions. Some DBAs are loath to use this script because it creates a temporary table, which will block if another space management transaction is caught behind the blocking lock. Although this is extremely unlikely, the same information can be obtained from the DBA_WAITERS view if necessary. The DBA_WAITERS view is created by Oracle's catblock.sql script.
Some application developers attempt to evade blocking locks by preceding all updates with a SELECT FOR UPDATE NOWAIT or SELECT FOR UPDATE SKIP LOCKED statement. However, if they allow user interaction between taking a sub-exclusive lock in this way and releasing it, then a more subtle blocking lock situation can still occur. If a user goes out to lunch while holding a sub-exclusive lock on a table, then any shared lock request on the whole table will block at the head of the request queue, and all other lock requests will queue behind it.
Diagnosing such situations and working out which session to kill is not easy, because the diagnosis depends on the order of the waiters. Most blocking lock detection utilities do not show the request order, and do not consider that a waiter can block other sessions even when it is not actually holding any locks.
Lock Detection Scripts
The following scripts can be used to track and identify blocking locks. The scripts shows the following lock situation.
Session 1 Session 2 select empno
from emp for update of empno;update emp set ename = 'M眉ller'
where empno = 7369;
This script shows actual DML-Locks (incl. Table-Name), WAIT = YES means
that users are waiting for a lock.WAI OSUSER PROCESS LOCKER T_OWNER OBJECT_NAME PROGRAM
--- ------- -------- ------- -------- ------------- --------------
NO zahn 8935 SCOTT - Record(s) sqlplus@akira
YES zahn 8944 SCOTT - Record(s) sqlplus@akira
NO zahn 8935 SCOTT SCOTT EMP sqlplus@akira
NO zahn 8944 SCOTT SCOTT EMP sqlplus@akira
This script show users waiting for a lock, the locker and the SQL-Command they are waiting for a lock, the osuser, schema and PIDs are shown as well.
Current Lock-Waits
OS_LOCKER LOCKER_SCHEMA LOCKER_PID OS_WAITER WAITER_SCHEMA WAITER_PID
---------- -------------- ---------- ----------- --------------- ----------
zahn SCOTT 8935 zahn SCOTT 8944
SQL_TEXT_WAITER
--------------------------------------------------------------------------
TX: update emp set ename = 'M眉ller' where empno = 7369
This is the original Oracle script to print out the lock wait-for graph in a tree structured fashion. This script prints the sessions in the system that are waiting for locks, and the locks that they are waiting for. The printout is tree structured. If a sessionid is printed immediately below and to the right of another session, then it is waiting for that session. The session ids printed at the left hand side of the page are the ones that everyone is waiting for (Session 96 is waiting for session 88 to complete):
WAITING_SESSION LOCK_TYPE MODE_REQUESTED MODE_HELD LOCK_ID1 LOCK_ID2 ----------------- ------------ -------------- ---------- --------- -------- 88 None 96 Transaction Exclusive Exclusive 262144 3206
The lock information to the right of the session id describes the lock that the session is waiting for (not the lock it is holding). Note that this is a script and not a set of view definitions because connect-by is used in the implementation and therefore a temporary table is created and dropped since you cannot do a join in a connect-by.
This script has two small disadvantages. One, a table is created when this script is run. To create a table a number of locks must be acquired. This might cause the session running the script to get caught in the lock problem it is trying to diagnose. Two, if a session waits on a lock held by more than one session (share lock) then the wait-for graph is no longer a tree and the conenct-by will show the session (and any sessions waiting on it) several times.
Distributed Transactions
For distributed transactions, Oracle is unable to distinguish blocking locks and deadlocks, because not all of the lock information is available locally. To prevent distributed transaction deadlocks, Oracle times out any call in a distributed transaction if it has not received any response within the number of seconds specified by the _DISTRIBUTED_LOCK_TIMEOUT parameter. This timeout defaults to 60 seconds. If a distributed transaction times out, an ORA-2049 error is returned to the controlling session. Robust applications should handle this exception in the same way as local enqueue deadlocks.
select name,value
from v$parameter
where name = 'distributed_lock_timeout';
NAME VALUE
----------------------------- ------
distributed_lock_timeout 60
ITL Entry Shortages
There is an interested transaction list (ITL) in the variable header of each Oracle data block. When a new block is formatted for a segment, the initial number of entries in the ITL is set by the INITRANS parameter for the segment. Free space permitting, the ITL can grow dynamically if required, up to the limit imposed by the database block size, or the MAXTRANS parameter for the segment, whichever is less.
Every transaction that modifies a data block must record its transaction identifier and the rollback segment address for its changes to that block in an ITL entry. (However, for discrete transactions, there is no rollback segment address for the changes.) Oracle searches the ITL for a reusable or free entry. If all the entries in the ITL are occupied by uncommitted transactions, then a new entry will be dynamically created, if possible.
If the block does not have enough internal free space (24 bytes) to dynamically create an additional ITL entry, then the transaction must wait for a transaction using one of the existing ITL entries to either commit or roll back. The blocked transaction waits in shared mode on the TX enqueue for one of the existing transactions, chosen pseudo-randomly. The row wait columns in V$SESSION show the object, file, and block numbers of the target block. However, the ROW_WAIT_ROW# column remains unset, indicating that the transaction is not waiting on a row-level lock, but is probably waiting for a free ITL entry.
The most common cause of ITL entry shortages is a zero PCTFREE setting. Think twice before setting PCTFREE to zero on a segment that might be subject to multiple concurrent updates to a single block, even though those updates may not increase the total row length. The degree of concurrency that a block can support is dependent on the size of its ITL, and failing that, the amount of internal free space. Do not, however, let this warning scare you into using unnecessarily large INITRANS or PCTFREE settings. Large PCTFREE settings compromise data density and degrade table scan performance, and non-default INITRANS settings are seldom warranted.
One case in which a non-default INITRANS setting is warranted is for segments subject to parallel DML. If a child transaction of a PDML transaction encounters an ITL entry shortage, it will check whether the other ITL entries in the block are all occupied by its sibling transactions and, if so, the transaction will roll back with an ORA-12829 error, in order to avoid self-deadlock. The solution in this case is to be content with a lower degree of parallelism, or to rebuild the segment with a higher INITRANS setting. A higher INITRANS value is also needed if multiple serializable transactions may have concurrent interest in any one block.
Check ITL Waits
The following SQL-Statement shows the number of ITL-Waits per table (Interested Transaction List). INITRANS and/or PCTFREE for those tables is to small (could also be that MAXTRANS is too small). Note that STATISTICS_LEVEL must be set to TYPICAL or ALL, MAXTRANS has been desupported in Oracle 10g and now is always 255 (maximum).
select name,value
from v$parameter
where name = 'statistics_level';NAME VALUE
------------------------------------ -----------
statistics_level TYPICALTTITLE "ITL-Waits per table (INITRANS to small)"
set pages 1000
col owner format a15 trunc
col object_name format a30 word_wrap
col value format 999,999,999 heading "NBR. ITL WAITS"
--
select owner,
object_name||' '||subobject_name object_name,
value
from v$segment_statistics
where statistic_name = 'ITL waits'
and value > 0
order by 3,1,2;
--
col owner clear
col object_name clear
col value clear
ttitle off
/
Conclusion
Exclusive Locks lock a resource exclusively, Share Locks can be acquired by more than one Session as long as the other Session holding a Share Lock have no open Transaction. A Share Lock can be "switched" from one Session to another.
Application developers can eliminate the risk of deadlocks by ensuring that transactions requiring multiple resources always lock them in the same order.
A DELETE CASCADE can start out as a simple, single-record delete from a harmless table could turn into an uncontrollable torrent of cascading deletes and stored database triggers.
Blocking locks are almost always TX (transaction) locks or TM (table) locks. Oracle always performs locking automatically to ensure data concurrency, data integrity, and statement-level read consistency. Usually, the default locking mechanisms should not be overriden.
For distributed transactions, Oracle is unable to distinguish blocking locks and deadlocks.
The most common cause of ITL entry shortages is a zero PCTFREE setting.
- show_blocking_sessions.zip (1.2 KB)
- 下载次数: 0
- show_dml_locks.zip (694 Bytes)
- 下载次数: 0
- show_missing_fk_index.zip (856 Bytes)
- 下载次数: 0
- utllockt.zip (2 KB)
- 下载次数: 0
发表评论
-
关于Oracle 版本
2015-10-10 10:23 0第一部分是“Version Number",也就是产 ... -
了解Oracle数据库的版本号
2015-10-10 10:20 0Major Database Release ... -
PDF 资料
2013-03-13 15:45 0Java design pattern --Bob ... -
Oracle sys和system用户、sysdba 和sysoper系统权限、sysdba和dba角色的区别 [转]
2013-03-12 14:17 1025sys和system用户区别 1)最重要的区别,存储的数 ... -
Oracle 用户、对象权限、系统权限 [转]
2013-03-12 14:12 0--============================ ... -
表分区分割脚本
2013-03-12 13:10 738表分区分割脚本 -
Oracle Session 视图[转]
2013-03-06 10:17 977v$session v$session_wait v$ ... -
10G中查看历史执行计划信息[转]
2013-03-01 11:02 3764现在总结下10G的,使用的是AWR报告中的信息,主要是查询 ... -
Oracle 表连接 [转]
2013-02-26 15:20 649Oracle 表之间的连接分为三种: 1. 内连接(自然 ... -
oracle的number类型精度、刻度范围 [转]
2013-02-26 15:06 5254一、 oracle 的 number 类型精度、刻度范围 ... -
Oracle Tablespace
2012-11-29 16:53 01. 几个重要的TableSpace SYSTE ... -
[转]Optimizing SPLIT PARTITION and SPLIT SUBPARTITION Operations
2012-11-27 15:11 913Optimizing SPLIT PARTITION and ... -
Oracle splitting partitions简单小结[转]
2012-11-27 15:12 997http://www.oracleonlinux.cn/201 ... -
When the explanation doesn't sound quite right
2012-10-30 13:05 0When the explanatio ... -
oracle中join的用法 .
2012-10-10 11:43 0oracle中join的用法8i: create ... -
[转]Oracle中Left Outer Join和外关联(+)的区别
2012-11-27 15:15 844外关联是Oracle数据库的专有语句 Left Outer ... -
[转]关于ORACLE的锁表与解锁总结
2012-09-29 11:11 0总结1:Oracle的锁表与解锁 selects.userna ... -
not in/not exists 的 null 陷阱
2012-09-27 11:07 0[转]not in/not exists 的 nul ... -
Oracle Database Link Tutorials,Examples to create, use, manage and drop them[转]
2012-09-21 10:54 0Oracle Database Link TutorialsE ... -
Understanding Oracle QUERY PLAN
2012-01-06 11:28 1164Understanding Oracle QUERY PLAN ...
相关推荐
Oracle性能诊断指南(Oracle Performance Diagnostic Guide)中专门有一部分是关于Hang/Locking问题的分析和解决方法。下面将详细介绍该部分所包含的知识点: 一、什么是“hang”或锁定问题? “Hang”问题是指...
### Oracle数据库中的事务处理与锁定揭秘 #### 一、引言 在开发高度并发和可扩展的数据库应用程序时,理解底层数据库如何管理事务至关重要。Oracle作为业界领先的数据库管理系统之一,其事务管理和锁定机制的设计...
which is this material, in your usage.Understanding Oracle Locking Internals 2LockingUnderstanding Oracle Locking Internals 3TableRow1Row2Row3Session1 Session2has updated the rowwants to update the ...
Oracle Database Transactions and Locking Revealed provides much-needed information for building scalable, high-concurrency applications and deploy them against the Oracle Database. Read this short, ...
乐观锁在Oracle数据库并发控制中的应用 乐观锁是一种在数据库管理系统中实现并发控制的方法,它假设在多数情况下读多写少的情况,因此在读取数据时不会加锁,只有在更新数据时才会检查在此期间是否有其他事务修改了...
由于Oracle Performance Diagnostic Guide中关于hang/locking部分的内容还在开发完善中,用户在使用时可能需要关注其最新版本,以便获取最新的诊断工具和方法。在处理hang问题时,可能还会涉及到一些高级技术,比如...
在安装过程中遇到的任何问题,都可以参考GI Installation Guide Linux.pdf,或者联系作者MPaularbear寻求帮助。 总之,安装Oracle 11.2.0.4在Oracle Linux 7.2上是一项复杂的工作,涉及到多个层面的系统配置,包括...
在Linux内核中,锁机制是确保并发执行的线程之间正确同步的关键工具。它用于保护共享资源,防止数据竞争和不一致状态的发生。对于驱动编写者来说,深入理解锁的原理和用法至关重要,因为驱动程序往往需要访问硬件...
《Unreliable Guide to Locking》是一份由Rusty Russell撰写的详尽文档,中文版由albcamus翻译,深入探讨了Linux内核中的锁定机制。这份文档是免费软件的一部分,遵循GNU通用公共许可协议发布,允许用户自由地分发、...
6. **并发控制**:Oracle使用行级锁定(Row-Level Locking)来实现并发控制,避免数据冲突。此外,还有读已提交(Read Committed)、可重复读(Repeatable Read)和串行化(Serializable)三种事务隔离级别。 7. **...
disk.locking ="FALSE" diskLib.dataCacheMaxSize= "0" scsi1.sharedBus ="virtual" 修改完成后保存。保存后打开虚拟机。 二、环境配置 Step1:创建用户 /usr/sbin/groupadd -g 1020 asmadmin /usr/sbin/...
5. **其他设置**:`disk.locking = "false"`确保磁盘在多节点之间可以同时访问,`diskLib.dataCacheMaxSize = "0"`等设置可能涉及数据缓存的配置,这些设置可能影响磁盘性能和并发访问。 6. **启动与验证**:在完成...
important database topics such as locking, concurrency controls, how transactions work, and redo and undo, and why it is important for you to know about these things. Lastly, I examine the physical ...
Oracle提供了事务管理和锁定机制,如ROW LEVEL LOCKING和SERIALIZABLE隔离级别,来确保数据一致性。 通过阅读《Oracle 12c PL/SQL程序设计终极指南》,你将深入理解这些概念,并学习到如何在实践中应用它们。这本书...
### 剪切自锁(Shear Locking)解析 #### 一、概述 剪切自锁(Shear Locking)是有限元分析中的一个重要概念,尤其在处理薄板或细长结构时尤为显著。该现象最早在六十年代被发现,当时人们注意到基于位移方法...
- **Locking and Concurrency**: GCS和GES确保多实例下的并发控制,避免数据冲突。 - **Parallel Execution**: RAC支持并行执行,使得大事务能够在多个实例上同时处理。 四、RAC部署与管理 1. **安装与配置**: 需要...