메뉴 건너뛰기

SAP 한국 커뮤니티

What Are Lock Objects ?

D.Y.Kim 2007.07.20 10:58 조회 수 : 7687 추천:28

What Are Lock Objects ?

In the majority of computer programs, data is input into the program, some processing is carried out on that data and the results are output from the program. This causes no problems whatsoever in a single user system, or where the output is going to the screen or a printed report.

However, in the case of writing data files on a multi-user system this can be fraught with danger in as much that the data in the file can be corrupted by containing the wrong results.

How can this happen ??

Let me introduce Ann and Bill. Ann is a data entry clerk working in a company entering sales orders onto a computer system such as SAP. Bill is an account payments clerk, entering account payments into the financial side of the system.

Coincidentally they happen to be updating the account of a very regular customer. Part of the update process on the entry of a sales order is to update the amount of money owed by the customer. From Bill's side of things, entering a Payment downdates the amount of money owed.

So, Ann starts entering her sales order. The computer system updates the account balance by reading the account balance, adding the new sales order value to it and then writing the account balance back to the record.

In between Anns program reading the account balance and updating it with the new figure, Bills program comes along and reads the account balance, downdates it with the payment and then writes it back to the record. This is what happens:


Code:
Ann                          Bill                Value
Enters Sales order
    Retrieves Amount                      100.00
    Adds Order Value                      10.00
                                                     ------
                                                  110.00

                   Enters Payment           50.00
                      Retrieves Amount    100.00
                                                    ------
                                                    50.00
Saves Order
    Updates Account Value              110.00
                     Saves Payment
                     Updates Amount       50.00
So, at the end of all that, the customers account is showing a balance of 50.00. Something wrong here.....

What needs to happen is that a mechanism needs to be put in place to prevent a second or subsequent users from accessing the data whilst another user is updating it:



Code:
Ann                          Bill                    Value
Enters Sales order
    Retrieves Amount                                 100.00
    Locks Record
    Adds Order Value                                  10.00
                                                     ------
                                                     110.00
                             Tries to enter payment
                             Record Locked - refused
Saves Order
    Updates Account Value                            110.00
    Unlocks record


                             Enters Payment           50.00
                                 Locks record
                                 Retrieves Amount    110.00
                                                     ------
                                                      60.00
                             Saves Payment
                                 Updates Amount       60.00
                                 Unlocks Record
This then gives the account the correct value of 60.00. This is essentially what record locks do. They deny access to data whilst that data is in a state of change.

Record locking Problems.

In any multiuser system, you can encounter problems when using record locking. The first problem is to create a generic procedure on what to do when you cannot lock a record (ie the lock is not granted). Generally all that needs to happen is that a message is displayed and the user is taken back to the start of the transaction.

However, when update programs start be run in the back ground, you can then start doing things like wait for a period of time, try again, wait for a another period of time and try again. If this continues for say ten times then you abandon the update and send some one a message... Another variation on this is to wait a random amount of time each time, or just give up on the first try.

The other thing to be aware of is that when you lock an object you must lock it(them...) in the same order each time otherwise you can end up in what is called Deadlock.

Deadlock occurs when you have to lock two or more objects. For example a customer record and then a gl account record. Another program also needs to lock the same two objects, but locks them in the reverse order - Gl Account then Customer. Your program grabs the customer, the other grabs the GL Account. You then try and grab the GL account and can't because it's locked so you wait. The other program tries to grab the Customer record and can't because you have it locked so that waits.... and waits.... and waits.... (if it doesn't have a sensible record locking policy in place).

When you unlock objects, unlock them in the reverse order that they were locked in. Ie Customer/Account Account/Customer.

Record Locking within SAP

There are two types of record locking available. Physical locks and Logical Locks. Physical locks are locks that are applied at the operating system level. A program requests a lock and it gets it. Another, totally unrelated program requests a lock of the same region on the disc and is refused. This is because both programs need to go via the operating system to get the locks. The O/S is the arbiter for the locks.

Logical locks are different. A logical lock depends on a flag in the record of the table, or records in a specific table specifying that the record is locked. A program will read the record, check the flag, if it's not set then it will set it and write it back to the disc. If it is set then the program treats that record as locked. SAP itself uses a dedicated table to hold the record locks. These locks can be seen via transaction SM12, or programatically via function modules ENQUE_READ and ENQUEUE_READ.

These logical locks are managed by a group of function modules known as 'Lock Objects'.

Having said that, SAP also has the ability to lock a record at Database level using the 'SELECT...FOR UPDATE' statement.

Creating A Lock Object

Lock objects are created using transaction SE11, and selecting the 'Lock Object' radio button. Enter the name of the lock obect in the relevant field (this must begin with the letters 'EZ').:



Enter the description for the lock object and click the 'Tables' tab. Enter the table name and select the lock mode:



What Is The Lock Mode ?.
The lock mode determines how the lock object will grant requests. There are three options that can be used. These are:


  • Exclusive, Cumulative
  • Shared
  • Exclusive, Not Cumulative



Exclusive Cumulative Mode.

Generally a lock object is used to prevent access by more than one person, and this is the lock mode that actually prevents that. This mode is generally the mode that will be used throughout your work.

Shared Mode.

Shared mode is a Read Lock. It allows other users to read the data, but not to write to it. Generally, when I am just displaying data, I do not lock the record at all, however, shgould the occasion arise whereby you must prevent the change of the data whilst just viewing it, then this is the lock mode to specify.

Exclusive Not Cumulative Mode.

In the Exclusive mode detailed above, the same transaction can reread the data from the same record as and when required. This mode prevents that. In other words, this mode locks the record in the table even against the program requesting the lock.....(!)

Seecondary Tables.

Multiple tables can be used to generate a lock object. These multiple tables are added to the secondary table list, however, when you build a set of custom lock objects it is generally easier to create a lock object for each table that you wish to lock and then call them in the same order each time.

For example, if you have two tables, a customer table and an accounts table. You could build a lock object to lock both the customer and accounts table at the same time, however, you may need to access the customer table without affecting the accounts table and vice versa. By using two distinct lock objects this can be done. You would still need two lock objects even if you included the accounts table in the initial customer lock object as well.

Once you have decided on the lock mode to use, click on the 'Lock Parameter' tab. This then display the criteria that will be used to lock the table:



The lock parameters are defined as which fields to use in the table, the defaults being the key fields on the table.

When you click the Save button and save/Activate your lock object, two function modules are produced. These function modules have the name ENQUEUE_* AND DEQUEUE_* where the * is the name of the lock object you have just created.

Using Lock Objects.

Lock objects are included in your program by using the 'Pattern' option available from the Edit menu, filling in the appropriate function module name:



Code:
*
*    Nothing fancy in the lock - just wait here till we get
*    it.
*
     Do.
        Call Function 'ENQUEUE_EZPCK_NUM'
          Exporting
            Mode_Zpck_Num        = 'E'
            Mandt                = Sy-Mandt
            Pcrn                 = c_Cntrl_Rec
            X_Pcrn               = ' '
            _Scope               = '2'
            _Wait                = ' '
            _Collect             = ' '
          Exceptions
            Foreign_Lock         = 1
            System_Failure       = 2
            Others               = 3.
        Case sy-subrc.
             When 1.
                  Wait up to 1 seconds.
             When Others.
                  Exit.
        EndCase.
     EndDo.
*
*    Error in Lock object ??
*
     If sy-subrc <> 0.
...
...
...
     Else.
*
*      Continue processing.
*
     EndIf.
What do the extra parameters mean ??

_Wait - The system will wait for a specified period of time if the lock cannot be granted. If during the period of this time the lock cannot be granted the function module wil raise the Foreign_Lock exception (ie some one else has the lock).

_Scope - This defines where the lock affects the data. With a '1', the lock is cleared once the transaction has passed the update request to the update task. '2' keeps the lock until the update task is complete. '3' generates two locks. The first is cleared when the transaction completes, the second when the update task has updated the record.

_Collect - If this is 'X' then the lock becomes Cumulative. If blank it is not.

Once the processing has been completed you should then free up the locks as soon as possible using the relevant DEQUEUE function:



Code:
     Add 1 to w_Pck_Num-Next_Pcrn.
     Update zPck_Num
            set Next_Pcrn = w_Pck_Num-Next_Pcrn
          where Pcrn = c_Cntrl_Rec.
     Call Function 'DEQUEUE_EZPCK_NUM'
       Exporting
         Mode_Zpck_Num       = 'E'
         Mandt               = Sy-Mandt
         Pcrn                = c_Cntrl_Rec
         X_Pcrn              = ' '
         _Scope              = '3'
         _Synchron           = ' '
         _Collect            = ' '.
번호 제목 글쓴이 날짜 조회 수
547 ABAP TUNNING sapjoy 2012.03.12 234725
546 New function vs Old function(obsolete) sapjoy 2014.03.31 127859
545 테이블Active시 (Warnings Occurred During Activation) 안나오게하는방법 [6] 양키 2012.03.29 99715
544 자주 사용하는 String 조작 명령어 [7] 양키(이경환) 2015.01.13 35130
543 collect 구문 [4] sapjoy 2006.12.03 27041
542 사용자 패스워드 변경 함수, 창 [11] sapjoy 2009.12.21 25848
541 R/3 용어 정의 Definitions [4] sapjoy 2007.01.23 23899
540 BAPI_PR_CREATE 구매요청 생성시에 사용하세요 [2] 노름마치 2007.12.10 23712
539 SELECT statement D.Y.Kim 2007.07.20 23649
538 문자열에 있는 값이 숫자만으로 되어있는지 문자가 포함됐는지 체크하는 함수 [3] 꿀단지 2011.10.11 19919
537 LIKE와 TYPE의 차이 [13] sapjoy 2006.12.06 19726
536 숫자입력 체크(Numeric character check) [1] 양키(이경환) 2014.01.28 19656
535 SDN -> SCN 변경되면서 Contents별로 바뀐 LINK 모음 [13] Wise 멘토 2012.07.06 19045
534 ALV LIST 진행시 LAYOUT 속성값 [18] kwon09 2007.04.11 17377
533 ABAP 핵심정리 [23] SARA 2007.03.14 17344
532 인터널 테이블 라인수 lines [8] sapjoy 2014.01.20 17306
531 ABAP 구문 총정리 [39] file Wise 멘토 2008.11.24 17175
530 SYST 시스템 변수 정리 [5] 아밥뽀 2014.08.23 17057
529 FOR ALL ENTRIES IN 구문 사용시 select 필드 선택시 주의사항. [7] 나침반친구 2007.03.13 17051
528 프로그램 정보(프로그램 리스트, PROGRAM LIST, PROGRAM TABLE) [3] sapjoy 2007.02.23 16888