数据库中的锁查询及相关关系

1.查询数据库中的锁

select * from v$lock;
select * from v$lock where block=1;

2.查询被锁的对象

select * from v$locked_object;

3.查询阻塞

查被阻塞的会话
select * from v$lock where lmode=0 and  type in ('TM','TX');

查阻塞别的会话锁
select * from v$lock where lmode>0 and  type in ('TM','TX');

4.查询数据库正在等待锁的进程

select * from v$session where lockwait is not null;

5.查询会话之间锁等待的关系

select a.sid holdsid,b.sid waitsid,a.type,a.id1,a.id2,a.ctime from v$lock a,v$lock b
where a.id1=b.id1 and a.id2=b.id2 and a.block=1 and b.block=0;

6.查询锁等待事件
select * from v$session_wait where event='enqueue';


1.关于V$lock表和相关视图的说明



Column
Datatype
Description

ADDR
RAW(4 | 8)
Address of lock state object

KADDR
RAW(4 | 8)
Address of lock

SID
NUMBER
Identifier for session holding or acquiring the lock

TYPE
VARCHAR2(2)
Type of user or system lock

The locks on the user types are obtained by user applications. Any process that is blocking others is likely to be holding one of these locks. The user type locks are:

TM - DML enqueue   

TX - Transaction enqueue

UL - User supplied

--我们主要关注TX和TM两种类型的锁

--UL锁用户自己定义的,一般很少会定义,基本不用关注

--其它均为系统锁,会很快自动释放,不用关注

ID1
NUMBER
Lock identifier #1 (depends on type)

ID2
NUMBER
Lock identifier #2 (depends on type)

---当lock type 为TM时,id1为DML-locked object的object_id

---当lock type 为TX时,id1为usn+slot,而id2为seq。

--当lock type为其它时,不用关注

LMODE
NUMBER
Lock mode in which the session holds the lock:

0 - none
1 - null (NULL)
2 - row-S (SS)
3 - row-X (SX)
4 - share (S)
5 - S/Row-X (SSX)
6 - exclusive (X)
--大于0时表示当前会话以某种模式占有该锁,等于0时表示当前会话正在等待该锁资源,即表示该会话被阻塞。

--往往在发生TX锁时,伴随着TM锁,比如一个sid=9会话拥有一个TM锁,一般会拥有一个或几个TX锁,但他们的id1和id2是不同的,请注意

REQUEST
NUMBER
Lock mode in which the process requests the lock:

0 - none
1 - null (NULL)
2 - row-S (SS)
3 - row-X (SX)
4 - share (S)
5 - S/Row-X (SSX)
6 - exclusive (X)
--大于0时,表示当前会话被阻塞,其它会话占有改锁的模式

CTIME
NUMBER
Time since current mode was granted

BLOCK
NUMBER
The lock is blocking another lock

0, 'Not Blocking', /* Not blocking any other processes */
1, 'Blocking', /* This lock blocks other processes */
2, 'Global', /* This lock is global, so we can't tell */

--该锁是否阻塞了另外一个锁
原文地址:https://www.cnblogs.com/lovewife/p/1427897.html