Willing-to-Wait Latches If a process acquires a latch in willing-to-wait mode, other processes requesting that latch with a willing-to-wait request will stack up waiting for the latch to
Trang 1T database processing that can all cause significant execution delays Users’
sessions can start to “pile up,” waiting for an available resource If you canproactively monitor the database and know when and where a problem is occurring,you’ll have an opportunity to tune these mechanisms before users even know any-thing is amiss
We’ll start with a discussion of locking, latching, and waiting and how they affectthe database When you understand the purpose and effects of these events, you canmore easily identify the problems that are most closely associated with them Fromthere, we’ll cover monitoring these mechanisms and tuning them based on the results
Latches and Locks
Much of the memory that Oracle allocates to the database process is shared ory—shared among all of Oracle’s processes for both reading and writing In manycases, Oracle needs to limit access to a particular area of memory to just one process.Limiting access to blocks and other memory structures helps ensure that otherprocesses do not interfere in the ongoing operations of other sessions Also, because
mem-of the concurrency and consistency requirements mem-of the database, Oracle must be able
to restrict access to user objects such as tables, clusters, partitions, and the data in therows in those objects
Two Oracle mechanisms facilitate some form of restricted access to memory blocks:
the latch and the lock (also known as an enqueue) Although very different in their
implementation of access control, latches and locks have something else in common:They both can be symptoms of database performance problems Much as fever andcoughing are symptoms of the flu, the behavior of latches and locks can help youdiagnose underlying problems in database operations By monitoring various statis-tics related to locks and latches, you can improve the effectiveness of your tuningefforts on the database and on SQL statements
What’s a Latch?
A latch is an elemental locking mechanism used by Oracle to serialize access to ous memory structures Oracle uses latches on structures that are expected to remainunlocked for a long period of time Latches protect memory structures and processessuch as redo-log buffer copy operations, the structures that manage the buffers in thedatabase buffer cache, and other operations that interact with the SGA
Trang 2vari-Oracle uses many different kinds of latches, and a given process may use morethan one latch In fact, more than one latch may be used for a single operation of aprocess For example, when an Oracle process needs to write to the redo log buffer,one or two latches are used to control that access, depending on the size of the redo
to be written
Latches are low-level locking mechanisms and are more restrictive than most ofthe locks used by Oracle Latching is an atomic operation In fact, locks use latches aspart of the overall locking mechanism With a few exceptions, latches restrict any kind
of access (read or write) to the memory area to the process that is holding the latch
Latch Contention
So, what happens during the life of a process waiting to acquire a latch? Getting alatch is like winning the Cannonball Run—the first one to the latch wins Morespecifically, the first process to request the latch acquires the latch Once a latch isacquired by a process, other processes wait based on the mode in which the latch wasrequested These modes are willing-to-wait mode and no-wait mode
Willing-to-Wait Latches
If a process acquires a latch in willing-to-wait mode, other processes requesting that
latch with a willing-to-wait request will stack up waiting for the latch to becomeavailable to them These waiting processes go through two distinct operations while
waiting: a spin operation, which involves continual attempts to reacquire the latch
over and over again If the subsequent latch get attempts are not successful after a
fixed period of spinning, the process enters a sleep operation.
The waiting process’s spin operation is essentially a timed loop The length of spintime is controlled by the hidden parameter _SPIN_COUNT Through each iteration ofthe spin process Oracle checks again to see if the latch is available Spin operations areCPU intensive because the process is active, looping and doing very little of worth
Still, spinning is much preferred to sleeping in most cases Spinning represents intenseuse of CPU resources, but sleeping generally has more negative ramifications on over-all process performance The reasons for this are discussed throughout this chapter
Sleeping occurs when the requesting process fails to get the latch after coming out
of the spin operation (or, in some cases, after awakening from another sleep tion) The sleep operation is a suspension of the thread or process for a given amount
opera-of time or until the sleeping process is awakened Putting a process in sleep modeworks the CPU fairly hard because of context switching (or the cost of moving theprocess and its related structures in and out of memory) When Oracle puts the process
Beyond Simple Database Management
P A R T
III
Trang 3company runs out of coal! As a waiting process moves from one sleep operation to thenext, the overall sleep time grows exponentially as Oracle increases the sleep cycleduration.
All this can have an adverse effect on the performance of the process becauselatches are not taken in any designated order So when a process wakes, the latch itwants may have already been acquired by another process The process sleeps yetagain, unable to acquire the latch it wants And with each sleep operation, the sleepduration increases, sometimes taking far longer than it should have to get the latch.One way to reduce the delay to a minimum is to raise the system’s _SPIN_COUNTparameter so that processes spin for a longer time before sleeping We’ll get into thislater in the sections on monitoring and tuning
Latch Wait Posting
Another measure for controlling sleep operations is to use latch wait posting When
latch wait posting is used, the process holding the latch will wake the sleeping processthat is waiting for the latch This is a more expensive arrangement, but it can decreasethe overall time waiting to acquire a latch
By default, only requests for the library cache and the shared pool latches use latchwait posting If you want to take advantage of latch wait posting for all latches, setthe hidden parameter _LATCH_WAIT_POSTING to 2 You can also disable this featurecompletely by setting the parameter to 0
TIP You can tell how many times a process has slept by looking for the Latch Free Waitstatistics in the V$SESSION_EVENT view, explained in the later section about Oracle waits
Monitor latching very carefully if you choose to change the _LATCH_WAIT_POSTING or the _SPIN_COUNT parameters, to make sure that the changes have apositive impact In particular, watch the V$LATCH and the V$SYSTEM_EVENT datadictionary views for excessive latch contention Look for significant wait times in thelatch free waits event in V$SYSTEM_EVENT In both views, look for increased wait timesfor latches in general (You can see why having TIMED_STATISTICS turned on is soimportant!)
When a willing-to-wait process uses latch wait posting, the process is still put tosleep because it cannot acquire the required latch Beforehand, however, the processposts a request for the latch in the latch wait list, which notifies processes that cur-rently own the latch that other processes are waiting Based on the latch wait list, theprocess acquiring the latch wakes up the sleeping process when the latch is freed
Trang 4No-Wait Mode Latches
When a process takes a latch in no-wait mode, the process will not sleep or spin in
order to wait for a given latch The process immediately tries to obtain the latchagain, without waiting, until it succeeds Generally, no-wait latches are used in caseswhere latch acquisition deadlocks between two or more processes might occur, andother latches have already been acquired at the same or lower level In this case, ifOracle cannot service the process’s request, the latches already allocated are releasedand the entire operation must be repeated Very few latches use no-wait mode
Parent/Child Latches
Oracle allows parent latches and child latches Structures that require multiple latches,
such as the shared pool, will have a parent latch (shared pool latch) and one or morechild latches Some parent latches have only one child (for example, the cache buffersLRU chain, which has one child latch in the database we use) and some have manychildren (for example, cache buffer chains, which has 512 in the database we use)
The use and number of parent/child latches vary among releases of Oracle
Latch Levels
The V$LATCH view (discussed shortly) includes a LEVEL# column Oracle assignslevel numbers to latches in order to avoid deadlocks Frequently, an operationrequires acquisition of multiple latches, and multiple processes may attempt toacquire the same latch Deadlock problems are prevented by Oracle’s assignment of
an order for the acquisition of latches The level numbers range from 0 to 15, andOracle acquires latches beginning at a lower level and proceeding to higher levels
When a process attempts to get a latch, Oracle checks to make sure that a latch at thesame or higher level is not already being held
Say that Processes 1 and 2 need Latches A and B If Process 1 acquires Latch B firstand then tries to allocate Latch A, and Process 2 grabs A first and then tries to acquire
B, you’d have a deadlock condition The two processes are each trying to acquire alatch already acquired by the other process Oracle prevents this by means of its latch-level architecture Processes 1 and 2 will always try to grab a latch first, because it’s alower-level latch If Process 1 grabs Latch A, Process 2 will spin or sleep until Process 1releases latch A Process 2 never tries to grab Latch B until it has acquired Latch A,thus preventing a potential deadlock situation
Important Latches for Monitoring
Oracle’s V$LATCH view comprises 152 different latch types (in Oracle 8.1.7) Whichones are the significant latches that you should be keeping an eye on? The following Beyond Simple Database Management
P A R T
III
Trang 5Database Buffer Cache Latches The cache buffers LRU chain is
respon-sible for protecting the blocks of the database buffer cache This important latch
is used to allow the addition of a new block into the database buffer cache
The cache buffers chain is requested when a process needs access to a block in the SGA.
Library Cache Latches The library cache latch must be obtained by a
process in order to add a new statement to the library cache The latch is not used
if the SQL statement is already in the library cache
The library cache pin latch must be obtained when a statement in the library cache
is to be reexecuted
The row cache objects latch must be acquired by a user process in order to access the
data dictionary
Redo Buffer Latches The well-known redo allocation latch is required so
that space can be allocated in the redo log buffer for redo log entries
The redo copy latch is uniquely handled by Oracle First of all, it’s not one latch but
several The number of redo copy latches is defined by the setting of the init.oraparameter _LOG_SIMULTANEOUS_COPIES, which is calculated by Oracle automat-ically, generally based on the CPU count of the system If the request for a latchfails, Oracle goes down the list of redo copy latches until it reaches the last one.Oracle tries to acquire this last latch in willing-to-wait mode, incurring the spin-ning and sleeping operations described earlier
Shared Pool Latch The shared pool latch is required when space in the
shared pool needs to be allocated or deallocated
Where to Find Latch Information
The primary views for information on latches are V$LATCH, V$LATCH_PARENT, andV$LATCH_CHILDREN
V$LATCH This view contains statistics for every type of latch used in Oracleand is critical to latch monitoring We will use the V$LATCH view later in thischapter as part of our proactive database monitoring and tuning strategy
Following are the important columns in this view:
• NAME and LEVEL#: These two columns identify the latch being monitoredand its level
• GETS: The number of times a willing-to-wait request for the latch was
suc-cessful This is not the number of requests, but the number of successes; the
count in this column does not increase until the latch get is successful
Trang 6• MISSES: The number of times a willing-to-wait request for a latch failed.
Each miss results in a spin operation This is a cumulative total of all failedattempts to get a latch So if a process fails four times before a successfullatch get, this column will show a 4 for those misses
• SLEEPS: The number of times a willing-to-wait request for this latch missedand the process ended up sleeping
• SPIN_GETS: The number of times a latch was acquired after the requestingprocess went into spin mode
• IMMEDIATE_GETS: The number of successful no-wait requests for the latch
• IMMEDIATE_MISSES: This column displays the number of failed no-waitrequests for the latch
• SLEEP1 through SLEEP4: The number of times the latch went through sleepoperations The SLEEP1 column lists the number of times a latch slept once,the SLEEP2 column lists the number of times that the latch swept twice, and
so on Columns SLEEP5 through SLEEP11 in V$LATCH are not used in Oracle8i
V$LATCH_PARENT and V$LATCH_CHILDREN These views provide
a more detailed look at the statistics for parent and child latches V$LATCH_
PARENT includes parent latches as well as latches with no associated child latches
Its columns are the same as for V$LATCH In V$LATCH_CHILDREN you get anadditional column, CHILD#
You can get a feel for the relationship of parent and child latches by using the lowing query (which only works in Oracle8i):
fol-SELECT b.name, b.num_parent, c.num_childFROM
(select name, count(*) num_parent from V$LATCH_parent group by name) b,(select name, count(*) num_child from V$LATCH_CHILDREN group by name) cWHERE b.name=c.name (+);
NOTE If you need details about the columns of V$LATCH, V$LOCK, and the other Oracleviews mentioned in this chapter, refer to the Oracle8i Reference Manual
Beyond Simple Database Management
P A R T
III
Trang 7What’s a Lock?
Multiple statement processing means an object may be needed by multiple transactions
at the same time A lock (also known as an enqueue) is an automatic internal mechanism
that protects access to Oracle data structures, similarly to the way latches protect access
to memory For example, when a process has issued a DML statement (INSERT, UPDATE,
or DELETE) that changes a row in a table, Oracle locks that row in order to preventother processes from changing it The lock remains in place until the related processcommits the transaction or issues a rollback that negates the DML action Rollbacks cantake a long time, which means the object remains locked for a long time
NOTE An Oracle oddity: If you ROLLBACK to a SAVEPOINT, the locks taken after POINT will be released—but they are not made available to any waiting transaction Newtransactions will be able to access rows affected by the locks, however
SAVE-Fortunately, Oracle handles locks automatically, so application developers don’t have
to worry about them Also, Oracle always uses the lowest level of locking possible, soyou don’t end up with locking that’s more restrictive than required Waiting sessionsare held in a queue until the lock is released Unlike latches, this queue is managed on
a first-in, first-out (FIFO) basis Therefore, the first process to request and wait for alock is the first process serviced after the lock is released Subsequent requestingprocesses will be handled in the order of the requests
NOTE Though Oracle handles locking automatically, it also provides tools needed byapplication developers to preemptively lock objects when the application design calls forcustom locking Unless otherwise noted, in this section we address issues related to auto-matic locking
Native Oracle locks do not prevent read access to the data in a table (but you canopt to use restrictive locks that do so) Keep in mind that when you query a table, the
data you see is the value of the data before application of any uncommitted
transac-tions from other sessions Thus, if you UPDATE in a SQL*Plus session but do notCOMMIT, you won’t see that data in a different SQL*Plus session Your UPDATE will
be visible in your session, however, even before you COMMIT it That’s Oracle dataconcurrency and consistency in action!
Trang 8Also, Oracle’s enqueue locking system provides a queuing system for lock requests.
Thus, if a process is blocked from acquiring a lock, that request for the lock is queued
up and will be processed in the order received Note that this differs from latching,where the fastest process gets the latch whether it was first or not Locking, on theother hand, provides a first-in first-out (FIFO) queueing system, that provides access
to resources to requesting processes in order
Working with the V$LOCK View
At the risk of belaboring the point, locking can cause serious performance problems and
is often the cause of very slow running queries To get information about who is lockingwhat objects in your database, a primary tool is the V$LOCK view It tells you aboutlocks on tables and rows, and who is taking those locks If users performing INSERTS,UPDATES, and DELETES are complaining that their systems aren’t moving smoothly,check V$LOCK—you’ll probably find the session that is causing the problem
Lock Types and Locking Modes
Locks come in different shapes and sizes Oracle uses the following:
Data or DML Locks Used to protect data, DML locks can lock an entiretable or specific rows of a table While it’s locked, your data is protected fromother users’ actions; and if you are making a change, other users’ actions will notconflict with that change
Data Dictionary or DDL Locks DDL locks are used for data dictionaryprotection (duh!) These locks generally are used to prevent the removal of objectsfrom the database, and to prevent changes in the structure of objects in the data-base while those objects are being used Dictionary locks are maintained duringboth the parse and execute stages of SQL statement processing and are held forthe lifetime of the transaction
Internal Locks These locks protect the internal structure of the databasedatafiles Internal locks are used in association with latches to protect variousinternal database structures
For each lock listed in the V$LOCK view, you’ll encounter codes representing thetypes of lock and graduated methods of locking objects Together, the codes tell youwhat type of locking is occurring (a DML row lock, for instance) and the extent of thelocking (exclusive or shared, for instance)
Lock Type Codes Beyond Simple Database Management
P A R T
III
Trang 9N OTE You can find more information on DDL locks by looking at theV$LOCKED_OBJECT view.
TABLE 17.1: DML LOCK TYPES
DML Lock Type Code Description
Row lock TX This is a row-level lock, the most granular lock in Oracle
Row-level locks are always exclusive
Table lock TM Acquired with various DML operations including INSERT,
DELETE, UPDATE, SELECT FOR UPDATE, and when the LOCKTABLE clause is used
User lock UL A lock created explicitly by the user via use of the
DBMS_LOCK package
TABLE 17.2: DDL LOCK TYPES
DDL Lock Type Code Description
Exclusive DDL lock N/A A lock on a resource being modified Prevents
simultane-ous DDL operations on the same object For example, youwon’t be able to drop a partition and move the same parti-tion at the same time
Share DDL lock N/A Prevents exclusive DDL locks from being taken against the
object locked Thus, this prevents a table from beingdropped while you are updating a procedure that refer-ences the table
Table 17.3 describes the internal lock codes that appear in the TYPE column ofV$LOCK In general, you don’t need to worry about them, but you may need to handle them in your monitoring scripts
Trang 10TABLE 17.3: INTERNAL LOCK TYPES
Lock code Description Lock Code Description
BL Buffer hash table instance NA to NZ Library cache pin instance (A Z
DF Data file instance QA QZ Row cache instance (A Z =
cache)
DL Direct loader parallel RT Redo thread global enqueue
index create
primary/secondary instance instance
DX Distributed transaction entry SN Sequence number instance
operations on a specific segment
serialization global enqueue
IV Library cache invalidation TS Temporary segment enqueue
(ID2=1)
LA to LP Library cache lock instance UN User name
lock (A P = namespace)
global enqueue
Beyond Simple Database Management
P A R T
III
Trang 11N OTE It’s not uncommon to see media recovery (MR) locks for each datafile in the database In Oracle8i, MR locks appear for each online datafile associated with theOracle database.
Oracle also allows NULL lock holders, which is not the same as “no lock.” If a sion has cached information about an object, the NULL lock causes the cached infor-mation to become invalidated if the associated resource is invalidated Table 17.4describes the DML locking modes and their codes (which appear in the LMODE col-umn of V$LOCK view)
ses-TABLE 17.4: ORACLE LOCKING MODES
Lock Mode Lock Mode Lock Type Description
Number in Represented LMODE Column
exists about an object Used to invalidate theinformation should the resource become invalid
A NULL lock is different from no lock at all.Row share 2 RS or SS Occurs when a transaction has locked rows
in a table with the intention of updatingthem This is the least restrictive of the DMLtable locks Does not prevent any type ofDML activity from occurring on the table.Row exclusive 3 RX or SX Occurs when a transaction has made a change
to a table row, via INSERT, UPDATE, or DELETEoperations Allows DML activity to continue onthe table Exclusive table access can beenforced via the LOCK TABLE command
Trang 12TABLE 17.4: ORACLE LOCKING MODES (CONTINUED)
Lock Mode Lock Mode Lock Type Description
Number in Represented LMODE Column
used Allows transactions only to query thetable involved in the lock, but does not pre-vent the use of SELECT FOR UPDATE Updates
by other transactions are not allowed
Share row 5 SRX or SSX Can only be obtained by one transaction at
use of the LOCK TABLE SHARE ROW SIVE MODE command Other transactionscan query the table, but no updates areallowed
EXCLUSIVE MODE command Prohibits anyother access to a table by any other transaction
Lock Conversions
Oracle converts locks rather than escalates them What’s the difference? Lock tion occurs when a given database holds several lower-level locks (such as row level)
escala-and escalates them to a higher level (such as table level) as an operation executes, in
order to reduce locking conflicts Oracle accomplishes this by conversion For example,
if you perform a SELECT FOR UPDATE, Oracle takes out row share (RS) locks on therows that are part of the SELECT FOR UPDATE statement Oracle also takes out a rowshare (RS) table-level lock As the transaction progresses and rows are changed, the RSlocks are converted to row exclusive (RX) table-level lock
Table 17.5 provides a summary of the various DML statements and the kinds oflocks they acquire
NOTE SELECT FOR UPDATE statements vis-à-vis locking are covered in more detail later
in this chapter, so read on
Beyond Simple Database Management
P A R T
III
Trang 13TABLE 17.5: DML STATEMENT LOCKING
Statement Type Lock Mode Acquired Causes Row Locks?
The ID1 and ID2 columns in the V$LOCK view take on a different meaningdepending on the value in the TYPE column Table 17.6 explains the contents of ID1and ID2 associated with the TYPE value
TABLE 17.6: V$LOCK’S ID1 AND ID2 COLUMN CONTENTS
Lock Type Column ID1 Meaning Column ID2 Meaning
Transaction (TX) Decimal value of the ROLLBACK Decimal value of the wrap number,
segment number and slot number or the number of times the
ROLL-BACK slot has been reused.Table lock (TM) Object ID of table being modified Always 0
Media recovery (MR) File ID of file against which the Always 0
lock is being held
An Example of Lock Monitoring Using V$LOCK
Let’s consider an example of using V$LOCK to handle a “blocking lock” state—that is,
a situation where one session’s locks are blocking another session from completing itswork A SQL*Plus session has updated a table record, but the transaction has not yetcommitted the record A second SQL*Plus session is trying to update the same record,without success
Trang 14Having read this far, you know the problem is that the first session is blocking thesecond session Once you’ve detected the blocking session, you can call the user andinvestigate Listing 17.1 provides a SQL script that detects the blocking session, usinginformation in the V$LOCK view.
Listing 17.1: Using V$LOCK to Find a Blocking Lock
Sqlplus scott/tiger In Session 1, we update employee 7369’s job description
SQL> SELECT empno, ename, job, sal from employee where empno=7369;
EMPNO ENAME JOB SAL - - - -
7369 Robert CLERK 800SQL> UPDATE employee set job=’PooBah’ where empno=7369;
1 row updated
Now, in a second session, we try to update the salary of the employee
Sqlplus scott/tigerSQL> UPDATE employee set sal=20000 where empno=7369;
Note that there is no message “1 row updated.” This session will hang here forever until Session 1 issues a COMMIT This is because both sessions are trying to change the same row If the user in the second session calls us wondering who is holding them up, we can query V$LOCK
1 SELECT sid, id1, id2, lmode, request, block
2 FROM v$lock3* order by block desc, id1, id2SQL> /
SID ID1 ID2 LMODE REQUEST BLOCK - - - - - -
Trang 15Here the blocking session is shifted to the top.
Where the BLOCK column=1, that SID is the bad guy So in this example it appears that Session 17 is causing the lock
Now we know that Session 17 is a blocking session because the block column ciated with that session is set to 1 If your V$LOCK query revealed several blockingsessions, how would you know the culprit is Session 17, and how would you find outwhat user is running Session 17?
asso-Let’s address the latter question first: Who is Session 17? Because we know the SID
of the blocking session (from the SID column in V$LOCK), we need only a simplequery against V$SESSION to find the offender Listing 17.2 shows an example of thisquery
Listing 17.2: Using V$SESSION to Find the User Assigned to a SID
SQL> l
1 select sid, serial#, username, osuser, machine, terminal, program
2 from v$session3* where sid=17SQL> /
SID SERIAL# USERNAME OSUSER MACHINE PROGRAM - - - - - -
17 10289 SCOTT MYNT_WORKSTN_MYID WORKGROUP\MYID SQLPLUS.EXEYou learn a lot from this query You see the user’s Oracle sign-on (SCOTT), the machineScott is working on (MYNT_WORKSTN_MYID), and the OSUSER logged in to the machine(MYID) You probably know enough now to go and ask the person about the lock
Of course, as a DBA, you never have enough information, do you? Before you lopoff this user’s head, let’s identify the object that is actually experiencing the lockingproblem You can do a couple of things here The V$LOCK view tells you whichobject is being blocked Perhaps even more valuable is the fact that V$SESSION tellsyou exactly what is blocking that session
Listing 17.2 executes a query against V$SESSION for the SID of the blocked session.Join it with DBA_OBJECTS, and voilà—you know what object is being blocked Morethan that, you’ll know the file number where the object is, the block number, andwhat row is being blocked Listing 17.3 shows you how to find this information, and
it has a query using the reported V$SESSION ROWID to find the row that is locked
Listing 17.3: Finding the Blocked Table/Row
SELECT a.sid, a.serial#, b.object_name, b.object_type, c.file_nameFROM v$session a, dba_objects b, dba_data_files c
Trang 16WHERE a.row_wait_obj#=b.object_id anda.row_wait_file#=c.file_id
and a.sid=15;
SID SERIAL# OBJECT_NAM OBJECT_TYPE FILE_NAME - - - - -
15 422 EMPLOYEE TABLED:\ORACLE\ORADATA\ORA816\ORA816_USERS_01.DBF
Get the restricted rowid information!
SQL> lSELECT row_wait_file#, row_wait_block#, row_wait_row# from v$sessionWHERE sid=15;
ROW_WAIT_FILE# ROW_WAIT_BLOCK# ROW_WAIT_ROW#
-
-3 4 -318 0
To look at the actual row, we need to convert these values into Hex with our handy dandy scientific calculator or one of the many available Decimal-to-Hex converter functions
The number 4318 = 10DE in Hex So, the final query to see the actual locked row shows up next!
SELECT empno, ename, job, sal from employeeWHERE rowid=dbms_rowid.rowid_to_extended(‘000010DE.0000.0003’,NULL,NULL,1);
EMPNO ENAME JOB SAL - - - -
7369 Robert PooBah 800
Lock Issues of Concern to DBAs
There are some specific lock-related issues meaningful to the DBA’s monitoring efforts,including lock interactions with foreign keys, and use of the SELECT FOR UPDATEstatement These issues have direct performance implications, so let’s get to them
Problems with Foreign Keys
If you take advantage of foreign key relationships in Oracle, it’s a good idea to index
Beyond Simple Database Management
P A R T
III
Trang 17there are no related records (Unless, of course, you have disabled the foreign key orset it to NORELY.) Full table scans can be a serious performance problem, so do your-self a favor and index the foreign key columns of the child table.
TI P Previous versions of Oracle had problems with unindexed foreign keys If youchanged a row in the child table, Oracle would take a table-level shared lock on the parenttable This is no longer the case with Oracle8i, which takes row exclusive locks instead Ifyou work with a version earlier than Oracle8i, index your foreign key columns to ensurethat you don’t get adverse locking
Problems with SELECT FOR UPDATE
By default, Oracle uses an optimistic locking strategy, which means that it assumes that
it will be able to get a lock on a required row when that row is required When you
employ the SELECT FOR UPDATE clause, however, it uses what is known as a simistic locking strategy This means a row-level lock is taken for all the rows that will
pes-be affected by the statement during the parse stage Rather than applying row-levellocks when the data is changed, Oracle applies row-level locks to each row to beimpacted by the statement before the statement executes As a result, the rows arelikely to be locked longer than they would be otherwise
So when, on occasion, you need to use the SELECT FOR UPDATE clause, be aware
of the impacts of doing so Review your application code and PL/SQL for all SELECTFOR UPDATE usage, and make sure that they’re warranted
Here’s an example: In the course of locking the rows in the table, the SELECT FORUPDATE statement reaches a record that is already locked, which causes the state-ment to fail Typically, the response of the application code is to retry the cursor until
it succeeds—an exceedingly inefficient approach In this situation, you could tryincluding the undocumented SKIP LOCKED keywords in the SELECT FOR UPDATEcommand The one caveat to this solution is that it will work only when you’re usingdynamic SQL
Another issue with SELECT FOR UPDATE statements involves the fact that locksare not cleared until the session is committed If users are firing off some massiveupdate to run over the weekend, watch out, because the locks that are acquired mightaffect users come Monday morning Always make sure users are aware of the impactsthat SELECT FOR UPDATE statements have on a system
Trang 18Wait Management
During database operations, various events occur, such as the database writer (DBWR)
writing to a datafile, a server process acquiring a lock on a buffer, or a process taking alatch on a row in the library cache Many of these events can experience performancedelays because of waits that occur during the event’s operation
Why worry about waits? Because wait statistics are a key indicator for determiningwhat’s ailing your database They tell you when your database is experiencing toomuch delay while waiting for log file switches, waiting for cached database blocks inthe SGA (buffer busy waits), waiting to get at a row in a table, and waiting on data dic-tionary rows (row cache lock waits)—to name just a few And when you know how tomonitor, analyze, and manage wait events, you have mastered another tool for mak-ing your database perform at top proficiency
You can examine events from the session level or at the level of the whole base, using several Oracle-supplied views that provide wait statistics for events Theseviews record a wide range and multiple classes of events, and you’ll see them usedthroughout this chapter
NOTE These views are primarily used for identifying events that cause significant waits
If a wait has not occurred for a particular event, it will not appear in any of these views
To determine the cause of a wait problem, three of these views are good tools for atop-down approach First, you look at the V$SYSTEM_EVENT view, which providessystemwide statistics When you have evidence of a systemwide wait problem, youthen look at the V$SESSION_EVENT view to get statistics for a specific session Onceyou have narrowed the problem down to a session and a specific type of wait, you look
at V$SESSION_WAIT for dynamic wait information In addition, the V$WAITSTAT viewgives you needed details when you’re tackling waits in a particular buffer Beyond Simple Database Management
P A R T
III
Trang 19sessions causing the blocking situations, and even how long the blocking has been in effect Later in this chapter we’ll discuss some additional views Oracle provides that present locking information in a format that is easier to read
The following sections examine each of these views and give suggestions for their use
NOTE The wait statistics views can provide timing information on waits, such as total time spent waiting and the average wait, if you have set the TIMED_STATISTICS parameter
to TRUE See “How Do You Get More Information from V$ Views?” in Chapter 15
Working with V$SYSTEM_EVENT
The V$SYSTEM_EVENT view provides a look at event waits in the database, system-wide This is the view we’ll use to monitor the database looking for wait problems that might be occurring It includes the name of the wait event, the total number of waits and timeouts, the total time waited, and the average time per wait (These last two statistics will not appear if TIMED_STATISTICS is not enabled.) The various wait events are discussed in a later section
Here’s a query against V$SYSTEM_EVENT:
SELECT * from v$system_event;
and the result:
EVENT TOTAL_WAITS TOTAL_TIMEOUTS TIME_WAITED AVERAGE_WAIT
- -
-latch free 54 54 0 0
pmon timer 634 628 0 0
checkpoint completed 1 0 0 0
buffer deadlock 1 1 0 0
buffer busy waits 45 1 0 0
log file sequential read 66 0 0 0
log file single write 13 0 0 0
log file parallel write 571 0 0 0
log file sync 657 1 0 0
db file sequential read 538 0 0 0
db file scattered read 145 0 0 0
db file single write 5 0 0 0
db file parallel write 53 0 0 0
db file parallel read 2 0 0 0
Trang 20direct path read 30 0 0 0
direct path write 20 0 0 0
instance state change 2 0 0 0
smon timer 10 5 0 0
library cache pin 19 3 0 0
library cache load lock 1 0 0 0
file identify 37 0 0 0
file open 116 0 0 0
Following is another query of V$SYSTEM_EVENT with a slightly narrower focus: SELECT event, total_waits, time_waited, average_wait FROM v$system_event; and the result: EVENT TOTAL_WAITS TIME_WAITED AVERAGE_WAIT - - -
-buffer busy waits 4 0 0
log file sequential read 23 0 0
log file single write 7 0 0
log file parallel write 133 0 0
LGWR wait for redo copy 2 0 0
log file sync 54 0 0
db file sequential read 603 0 0
db file scattered read 141 0 0
db file single write 5 0 0
db file parallel write 42 0 0
direct path read 20 0 0
Working with V$SESSION_EVENT Here’s an example of a query against V$SESSION_EVENT: Column timeouts heading “TIMEOUTS” SELECT * from v$session_event order by sid; and the result: SID EVENT TOTAL_WAITS TIMEOUTS TIME_WAITED AVERAGE_WAIT MAX_WAIT - - - -
-1 pmon timer 768 762 0 0 0
2 latch free 4 4 0 0 0 Beyond Simple Database Management
P A R T
III