Library Lock Analysis (vliblock.sql)
What This Script Does
Section titled âWhat This Script DoesâThis script analyzes library cache lock contention by identifying sessions currently waiting on library cache events and showing the specific database objects causing the contention. It provides detailed information about lock modes held and requested, helping diagnose parse-related performance issues, DDL blocking, and library cache contention problems.
The Script
Section titled âThe Scriptâ--need to be sysdbaselect decode(lob.kglobtyp, 0, 'NEXT OBJECT', 1, 'INDEX', 2, 'TABLE', 3, 'CLUSTER', 4, 'VIEW', 5, 'SYNONYM', 6, 'SEQUENCE', 7, 'PROCEDURE', 8, 'FUNCTION', 9, 'PACKAGE', 11, 'PACKAGE BODY', 12, 'TRIGGER', 13, 'TYPE', 14, 'TYPE BODY', 19, 'TABLE PARTITION', 20, 'INDEX PARTITION', 21, 'LOB', 22, 'LIBRARY', 23, 'DIRECTORY', 24, 'QUEUE', 28, 'JAVA SOURCE', 29, 'JAVA CLASS', 30, 'JAVA RESOURCE', 32, 'INDEXTYPE', 33, 'OPERATOR', 34, 'TABLE SUBPARTITION', 35, 'INDEX SUBPARTITION', 40, 'LOB PARTITION', 41, 'LOB SUBPARTITION', 42, 'MATERIALIZED VIEW', 43, 'DIMENSION', 44, 'CONTEXT', 46, 'RULE SET', 47, 'RESOURCE PLAN', 48, 'CONSUMER GROUP', 51, 'SUBSCRIPTION', 52, 'LOCATION', 55, 'XML SCHEMA', 56, 'JAVA DATA', 57, 'SECURITY PROFILE', 59, 'RULE', 62, 'EVALUATION CONTEXT', 'UNDEFINED') object_type, lob.KGLNAOBJ object_name, pn.KGLPNMOD lock_mode_held, pn.KGLPNREQ lock_mode_requested, ses.sid, ses.serial#, ses.username FROM x$kglpn pn, v$session ses, x$kglob lob, v$session_wait vsw WHERE pn.KGLPNUSE = ses.saddr and pn.KGLPNHDL = lob.KGLHDADR and lob.kglhdadr = vsw.p1raw and vsw.event like 'library%'order by lock_mode_held desc/Key Features
Section titled âKey Featuresâ- Real-Time Lock Analysis: Shows current library cache lock contention
- Object Identification: Identifies specific objects causing lock waits
- Lock Mode Analysis: Shows held vs. requested lock modes
- Session Information: Displays affected sessions and users
- Comprehensive Object Types: Covers all database object types
- DDL Blocking Detection: Identifies DDL operations causing blocks
- Parse Contention Analysis: Helps diagnose parse-related issues
@vliblock.sqlImportant: This script requires SYSDBA privileges to access X$ tables.
Required Privileges
Section titled âRequired Privilegesâ-- Must be connected as SYSDBACONNECT / AS SYSDBA
-- or have specific privileges:SELECT on X$KGLPNSELECT on X$KGLOBSELECT on V$SESSIONSELECT on V$SESSION_WAITSample Output
Section titled âSample OutputâOBJECT_TYPE OBJECT_NAME LOCK_MODE_HELD LOCK_MODE_REQUESTED SID SERIAL# USERNAME---------------- ------------------------------ -------------- --------------- ------- ------- ----------PACKAGE BODY DBMS_STATS 3 0 234 45691 HRPACKAGE BODY DBMS_STATS 0 3 456 23847 SALES_APP
PROCEDURE UPDATE_EMPLOYEE_SALARY 3 0 123 78934 DBA_USERPROCEDURE UPDATE_EMPLOYEE_SALARY 0 3 567 12456 HR_BATCH
TABLE EMPLOYEES 2 0 345 56789 HRTABLE EMPLOYEES 0 5 678 89012 DDL_USER
PACKAGE CUSTOM_UTILS 3 0 789 34567 APP_USERPACKAGE CUSTOM_UTILS 0 3 890 67890 APP_USER2Key Output Columns
Section titled âKey Output Columnsâ- OBJECT_TYPE: Type of database object (TABLE, PACKAGE, PROCEDURE, etc.)
- OBJECT_NAME: Name of the object being locked
- LOCK_MODE_HELD: Lock mode currently held by the session
- LOCK_MODE_REQUESTED: Lock mode being requested by waiting session
- SID: Session ID of the session
- SERIAL#: Serial number of the session
- USERNAME: Database username of the session
Understanding Library Cache Lock Modes
Section titled âUnderstanding Library Cache Lock ModesâLock Mode Values
Section titled âLock Mode ValuesâHeld Lock Modes
Section titled âHeld Lock Modesâ-- Lock modes held (KGLPNMOD):-- 0: No lock held-- 1: NULL lock-- 2: SHARE lock (S)-- 3: SHARE ROW EXCLUSIVE lock (SRX)-- 4: EXCLUSIVE lock (X)-- 5: EXCLUSIVE lock with immediate invalidationRequested Lock Modes
Section titled âRequested Lock Modesâ-- Lock modes requested (KGLPNREQ):-- 0: No lock requested-- 1: NULL lock requested-- 2: SHARE lock requested-- 3: SHARE ROW EXCLUSIVE lock requested-- 4: EXCLUSIVE lock requested-- 5: EXCLUSIVE lock with invalidation requestedLock Compatibility
Section titled âLock CompatibilityâCompatible Operations
Section titled âCompatible Operationsâ-- Multiple sessions can hold:-- NULL locks simultaneously-- SHARE locks simultaneously-- Mixed NULL and SHARE locksIncompatible Operations
Section titled âIncompatible Operationsâ-- Blocking scenarios:-- EXCLUSIVE lock blocks all other lock requests-- DDL operations require EXCLUSIVE locks-- Compilation requires SHARE ROW EXCLUSIVE locks-- Multiple sessions compiling same objectCommon Use Cases
Section titled âCommon Use Casesâ-
DDL Blocking Analysis
- Identify DDL operations waiting for locks
- Find sessions blocking DDL commands
- Analyze ALTER TABLE or DROP operations
- Support maintenance window planning
-
Parse Contention Diagnosis
- Identify parsing bottlenecks
- Analyze shared pool contention
- Find objects causing parse waits
- Support SQL tuning efforts
-
PL/SQL Compilation Issues
- Diagnose package compilation waits
- Identify dependency chain problems
- Analyze recompilation cascades
- Support development troubleshooting
-
Application Performance Issues
- Find library cache related slowdowns
- Identify locking patterns
- Analyze session blocking chains
- Support performance optimization
Advanced Analysis
Section titled âAdvanced AnalysisâDDL Operation Analysis
Section titled âDDL Operation AnalysisâDDL Blocking Patterns
Section titled âDDL Blocking Patternsâ-- DDL operations typically:-- Require EXCLUSIVE locks (mode 4 or 5)-- Block all other operations on the object-- Can cause widespread application waits-- May indicate maintenance window issuesDDL Impact Assessment
Section titled âDDL Impact Assessmentâ-- Assess DDL impact:-- Number of sessions affected-- Types of operations blocked-- Duration of blocking-- Application impact scopeParse Contention Analysis
Section titled âParse Contention AnalysisâParse Lock Contention
Section titled âParse Lock Contentionâ-- Parse contention indicators:-- Multiple sessions requesting SRX locks (mode 3)-- Contention on packages or procedures-- Shared pool pressure symptoms-- Cursor sharing problemsResolution Strategies
Section titled âResolution Strategiesâ-- Parse contention solutions:-- Optimize cursor sharing-- Reduce hard parsing-- Improve shared pool sizing-- Implement connection poolingObject Type Analysis
Section titled âObject Type AnalysisâHigh-Contention Object Types
Section titled âHigh-Contention Object Typesâ-- Objects prone to contention:-- PACKAGE BODY: Compilation and execution-- PROCEDURE/FUNCTION: Compilation conflicts-- TABLE: DDL operations-- VIEW: Definition changesContention Patterns
Section titled âContention Patternsâ-- Common contention scenarios:-- Package recompilation cascades-- Table structure modifications-- Procedure/function updates-- Development environment conflictsTroubleshooting Applications
Section titled âTroubleshooting ApplicationsâImmediate Response
Section titled âImmediate ResponseâSession Identification
Section titled âSession Identificationâ-- Identify problem sessions:-- Sessions holding EXCLUSIVE locks-- Long-running DDL operations-- Sessions with high lock mode values-- Users performing maintenanceQuick Resolution
Section titled âQuick Resolutionâ-- Immediate actions:-- Contact session owners-- Consider session termination-- Reschedule maintenance operations-- Implement workaroundsRoot Cause Analysis
Section titled âRoot Cause AnalysisâLock Chain Analysis
Section titled âLock Chain Analysisâ-- Analyze blocking chains:-- Identify root blocking session-- Map dependent sessions-- Assess cascade effects-- Plan resolution approachPattern Recognition
Section titled âPattern Recognitionâ-- Identify recurring issues:-- Frequent compilation conflicts-- Regular DDL blocking-- Application design problems-- Maintenance scheduling issuesPrevention Strategies
Section titled âPrevention StrategiesâDevelopment Practices
Section titled âDevelopment Practicesâ-- Prevent library cache contention:-- Coordinate development activities-- Use separate schemas for development-- Implement code review processes-- Schedule maintenance windowsApplication Design
Section titled âApplication Designâ-- Design considerations:-- Minimize dynamic DDL-- Use static SQL where possible-- Implement proper cursor sharing-- Consider connection poolingIntegration with Performance Monitoring
Section titled âIntegration with Performance MonitoringâReal-Time Monitoring
Section titled âReal-Time MonitoringâAlert Configuration
Section titled âAlert Configurationâ-- Set up alerts for:-- Library cache wait events-- Long-running DDL operations-- Parse contention thresholds-- Application response degradationDashboard Integration
Section titled âDashboard Integrationâ-- Dashboard components:-- Current library cache waits-- Top contended objects-- Session blocking relationships-- Lock mode distributionsHistorical Analysis
Section titled âHistorical AnalysisâTrend Monitoring
Section titled âTrend Monitoringâ-- Track historical patterns:-- Peak contention periods-- Recurring problem objects-- User activity correlations-- Maintenance impact analysisCapacity Planning
Section titled âCapacity Planningâ-- Support planning with:-- Parse workload trends-- Object usage patterns-- Resource requirement forecasts-- Maintenance window sizingPerformance Impact Assessment
Section titled âPerformance Impact AssessmentâApplication Impact
Section titled âApplication ImpactâResponse Time Analysis
Section titled âResponse Time Analysisâ-- Assess performance impact:-- Application response degradation-- User experience effects-- Transaction throughput reduction-- Service level violationsBusiness Impact
Section titled âBusiness Impactâ-- Business considerations:-- Critical application availability-- Peak business hour effects-- Customer service impact-- Revenue implicationsSystem Impact
Section titled âSystem ImpactâResource Utilization
Section titled âResource Utilizationâ-- System resource effects:-- CPU utilization patterns-- Memory allocation changes-- I/O operation impacts-- Network activity variationsStability Considerations
Section titled âStability Considerationsâ-- System stability factors:-- Cascade failure potential-- Recovery time requirements-- Backup operation impacts-- Maintenance window constraintsBest Practices
Section titled âBest PracticesâMonitoring Strategy
Section titled âMonitoring StrategyâRegular Monitoring
Section titled âRegular Monitoringâ-- Monitoring schedule:-- Real-time during peak hours-- Scheduled checks during maintenance-- Post-deployment validation-- Incident response proceduresProactive Detection
Section titled âProactive Detectionâ-- Early warning systems:-- Automated contention detection-- Performance threshold monitoring-- Trend analysis alerts-- Capacity planning reviewsResolution Procedures
Section titled âResolution ProceduresâIncident Response
Section titled âIncident Responseâ-- Response procedures:-- Rapid session identification-- Impact assessment protocols-- Escalation procedures-- Communication plansPrevention Measures
Section titled âPrevention Measuresâ-- Preventive actions:-- Development coordination-- Maintenance scheduling-- Application design reviews-- Performance testingRelated Scripts
Section titled âRelated Scriptsâ- vlibrary.sql - Library cache statistics
- vlibcache.sql - Library cache analysis
- vsession.sql - Session analysis
- vlock.sql - General lock analysis
Security Considerations
Section titled âSecurity ConsiderationsâAccess Control
Section titled âAccess Controlâ-- SYSDBA requirement considerations:-- Limit access to authorized personnel-- Implement proper authentication-- Monitor privileged access-- Maintain audit trailsData Sensitivity
Section titled âData Sensitivityâ-- Information exposure:-- Object names may be sensitive-- User information disclosure-- Application logic exposure-- Security policy considerationsAutomation and Scripting
Section titled âAutomation and ScriptingâAutomated Detection
Section titled âAutomated Detectionâ-- Automation opportunities:-- Scheduled contention checks-- Alert-driven analysis-- Performance dashboard integration-- Incident response automationCustom Extensions
Section titled âCustom Extensionsâ-- Script enhancements:-- Add timing information-- Include wait event details-- Correlate with other metrics-- Generate resolution suggestionsSummary
Section titled âSummaryâThis script is essential for:
- Library Cache Analysis - Real-time identification of library cache lock contention
- DDL Blocking Detection - Finding and resolving DDL operation conflicts
- Parse Contention Diagnosis - Identifying and resolving parse-related performance issues
- Session Troubleshooting - Understanding session blocking relationships and impacts
- Performance Optimization - Supporting systematic library cache performance improvement