메뉴 건너뛰기

SAP 한국 커뮤니티

What Are Lock Objects ?

D.Y.Kim 2007.07.20 10:58 조회 수 : 7686 추천: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            = ' '.
번호 제목 글쓴이 날짜 조회 수
447 <img src=b.gif>계속 남아있는 Debugger창 없에기(New Debugger)[추천:e-abap][추천:보나][추천:버미!] [14] 해처리 2011.01.07 8164
446 Number Range Object 변경/삭제 [4] file MadMax 2010.12.07 8159
445 BAPI_PO_CHANGE [1] 노름마치 2009.09.03 8139
444 Dynamic Internal Table [5] sapjoy 2007.02.11 8092
443 요약파일1 [7] file 밤의화신 2013.09.11 8039
442 Internal Table 알아보기 [15] file 양키 2010.12.20 8000
441 색상 정리 파일. [15] file 공백 2012.03.08 7973
440 CBO 테이블 데이터 UPLOAD 프로그램 [5] sapjoy 2006.12.21 7951
439 메세지 팝업창 뛰워주는 Function [2] file 양키 2013.08.19 7892
438 유지보수 view 생성 후 Field selection 화면 나오게 하려면? [7] file 나침반친구 2007.08.08 7892
437 평가영역 에서 자재 평가는 불일치성 합니다(이전전기시 에러) [1] sapjoy 2007.07.03 7867
436 [Function]달력 팝업창을 뛰워보자 [14] file 양키 2010.10.07 7824
435 [덤프해결] CX_SY_READ_SRC_LINE_TOO_LONG file 양키 2013.08.16 7790
434 온라인 스크린에서 SELECT-OPTION 사용하기 [1] sapjoy 2007.02.11 7785
433 move 구문 [4] sapjoy 2006.12.02 7730
» What Are Lock Objects ? D.Y.Kim 2007.07.20 7686
431 ALV에 아이콘 넣는 방법 [1] 푸른밤 2007.07.31 7607
430 BAPI_RESERVATION_CREATE1 MB21의 예약생성시 사용하세요. [2] 노름마치 2007.12.10 7602
429 SALV Webdynpro for abap tutorial [6] Wise 멘토 2011.11.15 7601
428 SAP Netweaver 설치 시스템사양 Tip [1] 양키 2012.09.21 7541