How Oracle Locking Works

download How Oracle Locking Works

of 8

Transcript of How Oracle Locking Works

  • 8/17/2019 How Oracle Locking Works

    1/8

    How Oracle Locking Works Myth: Oracle has a Central Locking SystemWhen a transaction updates a row, it puts a lock so that no one can update the same row until it commits.When another transaction issues an update to the same row, it waits until the first one either commits or rolls back.After the first transaction performs a commit or rollback, the update by the second transaction is executed immediately,since the lock placed by the first transaction is now gone.How exactly does this locking mechanism work? Seeral !uestions come to mind in this context"#. $s there some kind of logical or physical structure called lock%

    &. How does the second transaction know when the first transaction has lifted the lock%

    '. $s there some kind of (pool) of such locks where transactions line up to get one%

    *. $f so, do they line up to return it when they are done with the locking%

    +. $s there a maximum number of possible locks%

    . $s there something called a block leel lock% Since Oracle stores the rows in blocks, when all or the ma-ority of rowsn the blocks are locked by a single transaction, doesnt it make sense for to lock the entire block to consere the number ofocks%

    /. 0he preious !uestion brings up another !uestion 1 does the number of actie locks in the database at any pointreally matter%

    f you are interested to learn about all this, please read on.

    Lock Manager:Since locks coney information on who has what rows modified but not committed, anyone interested in making the updatemuch check with some sort of system that is aailable across the entire database.

    So, it makes perfect sense to hae a central locking system in the database, doesnt it% 2ut, when you think about it, acentral lock manager can !uickly become a single point of contention in a busy system where a lot of updates occur.Also, when a large number of rows are updated in a single transaction, an e!ually large number of locks will be re!uired aswell.0he !uestion is" how many% One can guess3 but it will be at best a wild one. What if you guessed on the low side and thesupply of aailable locks is depleted% $n that case some transactions cant get locks and therefore will hae to wait 4or,worse, abort5.6ot a pleasant thought in a system that needs to be scalable.0o counter such a traesty you may want to make the aailable supply of locks really high.What is the downside of that action% Since each lock would potentially consume some memory, and memory is finite, itwould not be adisable to create an infinite supply of locks.Some databases actually hae a lock manager with a finite supply of such locks.7ach transaction must ask to get a lock from it before beginning and relin!uish locks to it at the completion.n those technologies, the scalability of application suffers immensely as a result of the lock manager being the point ofcontention.n addition, since the supply of locks is limited, the deelopers need to commit fre!uently to release the locks for othertransactions.When a large number of rows hae locks on them, the database replaces the row locks with a block leel lock to coer all therows in the block 1 a concept known as lock escalation.Oracle does not follow that approach. $n Oracle, there no central lock manager, no finite limit on locks and there is no suchconcept called lock escalation. 0he deelopers commit only when there is a logical need to do so3 not otherwise.

    Lock Management in OracleSo, how is that approach different in case of Oracle% 8or starters, there is no central lock manager.2ut the information on locking has to be recorded somewhere.

    Where then% Well, consider this" when a row is locked, it must be aailable to the session, which means the sessions sererprocess must hae already accessed and placed the block in the buffer cache prior to the transaction occurring.0herefore, what is a better place for putting this information than right there in the block 4actually the buffer in the buffercache5 itself%Oracle does precisely that 1 it records the information in the block.When a row is locked by a transaction, that nugget of information is placed in the header of the block where the row isocated.When another transaction wishes to ac!uire the lock on the same row, it has to access the block containing the row anyway4as you learned in 9art # of this series5 and upon reaching the block, it can easily confirm that the row is locked from theblock header.A transaction looking to update a row in a different block puts that information on the header of that block.0here is no need to !ueue behind some single central resource like a lock manager.Since lock information is spread oer multiple blocks instead of a single place, this mechanism makes transactions immenselyscalable.2eing the smart reader you are, you are now hopefully excited to learn more or perhaps you are skeptical. :ou want to knowthe nuts and bolts of this whole mechanism and, more, you want proof. We will see all that in a moment.

    http://arup.blogspot.com/2010/12/100-things-you-probably-didnt-know.htmlhttp://arup.blogspot.com/2010/12/100-things-you-probably-didnt-know.htmlhttp://arup.blogspot.com/2010/12/100-things-you-probably-didnt-know.html

  • 8/17/2019 How Oracle Locking Works

    2/8

    Transaction Address2efore understanding the locks, you should understand clearly what a transaction is and how it is addressed.A transaction starts when an update to data such as insert, update or delete occurs 4or the intention to do so, e.g. S7L7;08O< =9>A075 and ends when the session issues a commit or rollback.Like eerything else, a specific transaction should hae a name or an identifier to differentiate it from another one of thesame type.7ach transaction is gien a transaction $>.When a transaction updates a row 4it could also insert a new row or delete an existing one3 but we will coer that little latern this article5, it records two things"

    0he new alue

    0he old alue0he old alue is recorded in the undo segments while the new alue is immediately updated in the buffer where the row isstored.0he data buffer containing the row is updated regardless of whether the transaction is committed or not.:es, let me repeat 1 the data buffer is updated as soon as the transaction modifies the row 4before commit5.f you didnt know that, please see the 9art # of this series.=ndo information is recorded in a circular fashion.When new undo is created, it is stored in the next aailable undo (slot).7ach transaction occupies a record in the slot.After all the slots are exhausted and a new transaction arries, the next processing depends on the state of the transactions.f the oldest transaction occupying any of the other slots is no longer actie 4that is either committed or rolled back5, Oraclewill reuse that slot.f none of the transactions is inactie, Oracle will hae to expand the undo tablespace to make room.n the former case 4where a transaction is no longer actie and its information in undo has been erased by a newtransaction5, if a long running !uery that started before the transaction occurred selects the alue, it will get an ORA-!!!error"2ut that will be coered in a different article in the future.f the tablespace containing the undo segment cant extend due to some reason 4such as in case of the filesystem beingcompletely full5, the transaction will fail.Speaking of transaction identifiers, it is in the form of three numbers separated by periods.0hese three numbers are"

    =ndo Segment 6umber where the transaction records its undo entrySlot? in the undo segmentSe!uence? 4or wrap5 in the undo slot

    0his is sort of like the social security number of the transaction. 0his information is recorded in the block header. Lets seethe proof now through a demo.

    #emo8irst, create a table"

    SQL> create table itltest (col1 number, col2 char(8));

    nsert some rows into the table.

    SQL> begin2 for i in 1..10000 loop insert into itltest !alues (i,"#");

    $ en% loop;& commit;

    ' en%;

    of this transaction, Oracle proides a special package CdbmsDtransaction. Here is how you use it.

  • 8/17/2019 How Oracle Locking Works

    3/8

    Lets see another demo. =pdate one row"

    SQL> up%ate itltest set col2 5 "6" 4here col1 5 1;

    1 ro4 up%ate%.

    n the same session, check the transaction $>"

    SQL> select %bms*transaction.local*transaction*i% from %ual;

    L+-L*/-S-+*3333333333333333333333333333333333333333333333333333333333333333333333333.2.$0$8$

    1 ro4 selecte%.

    0here you see 1 the transaction $>. 0he three numbers separated by period signify undo segment number, slot? and record?respectiely. 6ow perform a commit"

    SQL> commit;

    ommit complete.

    ;heck the transaction $> again"

    SQL> select %bms*transaction.local*transaction*i% from %ual;

    L+-L*/-S-+*3333333333333333333333333333333333333333333333333333333333333333333333333

    1 ro4 selecte%.

    0he transaction is gone so the $> is null, as expected.

    Since the call to the package must be in the same transaction 4and therefore in the same session5, how can you check the

    transaction in a different session% $n real life you will be asked to check transaction in other sessions, typically applicationsessions. Lets do a slightly different test. =pdate the row one more time and check the transaction"

    SQL> up%ate itltest set col2 5 "6" 4here col1 5 1;

    1 ro4 up%ate%.

    SQL> select %bms*transaction.local*transaction*i% from %ual;

    L+-L*/-S-+*3333333333333333333333333333333333333333333333333333333333333333333333310.2&.1$7

    1 ro4 selecte%.

    8rom a different session, check for actie transactions. 0his information is aailable in the iew I0

  • 8/17/2019 How Oracle Locking Works

    4/8

    nterested Transaction List":ou must be eager to know about the section of the block header that contains information on locking and how it records it.t is a simple data structure called $nterested Transaction List% &$TL', a list that maintains information on transaction. 0he0L contains seeral placeholders 4or slots5 for transactions. When a row in the block is locked for the first time, thetransaction places a lock in one of the slots. $n other words, the transaction makes it known that it is interested in some rows4hence the term $nterested 0ransaction List5. When a different transaction locks another set of rows in the same block, thatnformation is stored in another slot and so on. When a transaction ends after a commit or a rollback, the locks are releasedand the slot which was used to mark the row locks in the block is now considered free 4although it is not updatedmmediately C fact about which you will learn later in a different installment5.

    M=pdated Nan &&, &B## M0hank you,

  • 8/17/2019 How Oracle Locking Works

    5/8

    A session comes in and updates the row

  • 8/17/2019 How Oracle Locking Works

    6/8

    hae used two different colors to show the locks 4as shown by the star symbol5 and the color of the $0L entry.

    As you can clearly see, when a transaction wants to update a specific row, it doesnt hae to go anywhere but the blockheader itself to know if the row is locked or not. All it has to do is to check the $0L slots. Howeer $0L alone does not showwith #BBR accuracy that row is locked 4again, something $ will explain in a different installment5. 0he transaction must go tothe undo segment to check if the transaction has been committed. How does it know which specifci part of the undosegment to go to% Well, it has the information in the $0L entry. $f the row is indeed locked, the transaction must wait andretry. As soon as the preious transaction ends, the undo information is updated and the waiting transaction completes itsoperation.

    So, there is in fact a !ueue for the locks, but itQs at the block leel, not at the leel of the entire database or een thesegment.

    #emo0he proof is in the pudding. Lets see all this through a demo. 6ow that you know the transaction entry, lets see how it isstored in the block header. 0o do that, first, we need to know which blocks to look for. So, we should get the blocks numberswhere the table is stored"

    SQL> select file*i%, relati!e*fno, e#tent*i%, bloc=*i%, bloc=s2 from%ba*e#tents 4heresegment*name 5 "LS";

    alter s6stem %ump %atafile bloc= min &' bloc= ma# &8;

    S6stem altere%.

    0his will create a tracefile in the user dump destination directory. $n case of Oracle ##g, the tracefile will be in the diagstructure under FdiagFrdbmsFFFtrace directory. $t will be most likely the last tracefile generated. :ou can also get theprecise name by getting the OS process $> of the session"

    SQL> select p.spi%2 from!9session s, !9process p 4heres.si% 5 (select si% from !9m6stat 4here ro4numB 2)$ an%p.a%%r 5 s.pa%%r

    &

    SC3333333333333333333333337202

    1 ro4 selecte%.

    6ow look for a file named DoraDT&B&.trc. Open the file in i and search for the phrase ($tl). Here is an excerpt from the file"

    tl:i%ba

  • 8/17/2019 How Oracle Locking Works

    7/8

    0his is how Oracle determines that there is a transaction has locked the row and correlates it to the arious components inthe other areas 1 mostly the undo segments to determne if it is actie. 6ow that you know undo segments holds thetransaction details, you may want to know more about the segment. select G from %ba*%ata*files

    2> 4here file*i% 5 ;

    select si%, username2 from!9session 4heresa%%r 5 "$0-8$";

    S S/-D333 33333333

  • 8/17/2019 How Oracle Locking Works

    8/8

    12 -/C

    0here you go 1 you now hae the S$> of the session. And now that you know the S$>, you can look up any other releant dataon the session from the iew IS7SS$O6.

    TakeawaysHere is a summary of what you learned so far"#. 0ransaction in Oracle starts with a data update 4or intention to update5 statement. Actually there are someexceptions which we will coer in a later article.

    &. $t ends when a commit or rollback is issued

    '. A transaction is identified by a transaction $> 4J$>5 which is a set of three numbers 1 undo segment?, undo slot? andundo record? C separated by periods.

    *. :ou can iew the transaction $> in the session itself by calling dbmsDtransaction.localDtransactionDid function.

    +. :ou can also check all the actie transactions in the iew Itransaction, where the columns J$>=S6, J$>SLO0 andJ$>SG6 denote the undo segment?, undo slot? and undo rec? C the alues that make up the transaction $>.

    . 0he transaction information is also stored in the block header. :ou can check it by dumping the block and looking forthe term ($tl).

    /. 0he Itransaction iew also contains the session address under S7SDA>>< column, which can be used to -oin with theSA>>< column of Isession iew to get the session details.

    . 8rom the session details, you can find out other actions by the session such as the username, the SGL issues, themachine issued from, etc.