메뉴 건너뛰기

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            = ' '.
번호 제목 글쓴이 날짜 조회 수
447 Five Different "User Types" D.Y.Kim 2007.07.20 4779
446 T_CODE [9] BlackBean 2007.05.29 4301
445 FOR ALL ENTRIES IN 구문 사용시 select 필드 선택시 주의사항. [7] 나침반친구 2007.03.13 17019
444 변수 선언과 관련된 TIP [5] 나침반친구 2007.03.05 4674
443 SELECT statement D.Y.Kim 2007.07.20 23647
442 data [2] sapjoy 2006.12.03 16722
» What Are Lock Objects ? D.Y.Kim 2007.07.20 7687
440 ABAP/4 Optimization Techniques [1] sapjoy 2007.06.30 4894
439 CHECK - special for reports with logical databases [5] sapjoy 2006.12.02 4846
438 제가 모은 팁들입니다. [62] file 풍운사랑 2007.09.07 5541
437 Image를 화면에 보여주는 방법 [1] 정두영 2007.08.30 6001
436 설명이 비교적 자세하고 원리를 알수 있는 효과적인 ABAP코딩 문서.doc [13] file 박영신 2007.07.26 4041
435 일자에 포멧에 맞게 자동으로 처리하는 프로그램 [1] 박종갑 2007.07.13 3741
434 System Administration Made Easy - Performace file 박진만 2007.06.26 2985
433 excel macro SAP HELP sapjoy 2007.06.04 4442
432 ABAP DOCUMENT [2] sapjoy 2007.02.11 4478
431 ABAP 문법 2nd [8] file 아일락 2007.08.20 3914
430 평가영역 에서 자재 평가는 불일치성 합니다(이전전기시 에러) [1] sapjoy 2007.07.03 7870
429 텍스트파일 다운받을때 유니코드 문제 해결 [8] file 솔로몬 2007.06.28 13791
428 너무도 당연해서 가끔 잊곤하는 공기와 같은 존재 'F1' key [5] 백혜정 2007.09.19 4034