Lock Objects and the SAP Lock Concept
|
This content was generated with the assistance of AI and should be verified against the official documentation before being relied on in production. |
Two clerks open the same expense claim on their screens, both change the total and both press Save. Without a protection the second save silently overwrites the first, and one clerk’s work is lost. SAP systems prevent this with locks: before a program changes a claim, it asks the system to mark that claim as "in use", and anyone else who asks for the same claim while the mark is set is told no. This page explains how the mark is defined (a lock object in the ABAP Dictionary), what kinds of mark exist (the lock modes), how a program sets and removes it, where the system keeps the marks, and how the RESTful Application Programming Model (RAP) does the same job for you. It is written against Standard ABAP release 8.16 and ABAP for Cloud Development release 9.20 (2608). Lock objects and the lock mechanism exist in classic Standard ABAP on premise and in ABAP Cloud alike, but the way a program calls them differs: classic code may call the generated function modules directly, while ABAP Cloud code uses a class that wraps them. Every listing on this page needs lock objects, the ABAP Dictionary and an enqueue server, so each one is labelled as requiring an SAP system and was not run here.
Before you read
-
Database Tables and Structures: the table
zexp_claimand its key fields, which the lock object below is built on. -
ABAP SQL: Writing Data: database LUWs, SAP LUWs and
COMMIT WORK, because the life of a lock follows them. -
Memory Organization and Sessions: what a user session and an internal session are.
-
RAP business objects, behavior definitions and draft handling have pages of their own; this page only shows what they do about locks.
Key terms
-
SAP lock: a logical lock, based on a lock object, that is kept in the lock table and does not exist on the database.
-
Lock object: a repository object in the ABAP Dictionary that says which tables and which key fields a lock covers.
-
Lock mode: the kind of lock (S, E, X or O) that decides which other requests are accepted while it exists.
-
Enqueue server: the part of the system that holds the lock table and decides whether a lock request collides with an existing lock.
-
Lock table: the table in the memory of the enqueue server that holds one entry for each lock that is set.
-
Lock master: the entity of a RAP business object whose instance is locked whenever any instance of a lock dependent entity below it is locked.
Why a database lock is not enough
The database already locks rows while it changes them: an UPDATE marks the changed rows until the database LUW ends. That
is too short for an expense claim. A clerk opens a claim, spends two minutes typing, and only at the very end does the
program write to the database. A database lock held for those two minutes would block the database for everybody, and a
database LUW cannot even span the screens of one dialog. The Keyword Documentation says it directly: SAP locks must be
maintained for the duration of an SAP LUW, so different work processes, and even different application server instances,
must be able to handle them.
The SAP lock solves this by being a separate, logical lock. The SAP Lock Concept page states the difference: in an SAP transaction an enqueue lock is set when you view or change data, and the system also sets a database lock, which exists for a much shorter time. Unlike a database lock, an enqueue lock can be set across several database LUWs. The database does not know about it at all.
Two consequences follow, and the rest of the page builds on them.
-
The lock works only if every program that changes the data asks for it. The Dictionary documentation says that a lock protects the records against changes by another program only if that program also requests a lock before accessing the data. A program that goes straight to the database with an
UPDATEis not stopped. -
A program that sets a lock must also remove it, or the system removes it at a defined moment (end of the transaction, end of the update, end of the draft). Section "How long a lock lives" lists those moments.
The lock object
A lock object is a repository object of the ABAP Dictionary. It names the tables whose rows a lock covers and, for each table, which key fields identify the rows. The Keyword Documentation defines it as the basis of SAP locks: the lock covers one or more rows of a single table, or rows of several tables linked by foreign key dependencies. A lock object that spans a header table and its item table lets one lock protect a whole document, such as a claim and all its items.
The fields that identify the rows are the lock arguments. The Dictionary documentation says the lock argument of a table consists of the key fields of that table. When you set a lock, you pass a value for each argument; a field left out locks all values of that field, which is called a generic lock. The simplest lock object has one table, and its lock argument is that table’s primary key.
Each table of the lock object also gets a lock mode, the default kind of lock for that table. The next section lists the modes. The default is only a default: the program can pass another mode when it sets the lock.
Rules from the Dictionary documentation that a newcomer would otherwise learn the hard way:
-
The name of a lock object must begin with
E, for "enqueue". -
All other tables of the lock object must be linked to the primary table through foreign keys, and only some foreign key relationships are valid.
-
The Allow RFC attribute decides whether the generated function modules can be called from another system.
-
Lock objects are transported, not their generated function modules. The generated modules are created again on every activation, so you must not change them and must not transport the function groups that hold them.
In this section’s running example, the claim table is zexp_claim with the key fields client and claim_id. A lock object
for it could be called EZEXP_CLAIM, with the table zexp_claim, the lock argument claim_id and the lock mode E. The
client field is a key field too, and the lock is client specific; the unmanaged RAP sample later on this page passes only the
business key, not the client.
Lock objects are created in ADT with the wizard New, Other ABAP Repository Object, Dictionary, Lock Object (available from AS ABAP 7.53), or in the older Repository Browser or SE11 screens described on Classic Tools: SE80 and SE11. The ADT wizard asks for a name, a description, a package, a primary table and a transport request.
Lock modes
The mode tells the enqueue server what to do when a second request arrives for the same data. The SAP Lock Concept page lists four modes that really set a lock.
| Mode | Name | What it means |
|---|---|---|
|
Shared |
Several users can hold it at the same time, in display mode. Further S requests are accepted, because they are cumulated. |
|
Exclusive |
One user can read and change. The same user may request it again, because E is cumulated. Another user’s request collides. |
|
Exclusive, non-cumulative |
Like E, but the same transaction can request it only once. Any further request, even from the same transaction, collides. |
|
Optimistic |
Behaves like S first and can later be converted into an E lock. |
The documentation also names further modes that only check for collisions without setting a lock; they never appear in the lock table and are not covered here.
Two locks on the same data collide when all of the following are true: the table name is the same, the lock argument is the same in every position (a wildcard position matches any character), and at least one of the two locks is not in mode S. Two shared locks therefore never collide, and an exclusive lock collides with any other lock on the same data. When the locks collide, the system also checks the owners: the same owner may request an E lock again, but a request in mode X is rejected even then.
Source: SAP Lock Concept and Collision Check of Locks
The generated function modules
When you activate a lock object, the system generates two function modules from it. Their names are the prefixes ENQUEUE_
and DEQUEUE_ followed by the name of the lock object, for example ENQUEUE_EZEXP_CLAIM. A function module is an old kind of
reusable procedure that is called with CALL FUNCTION; you do not write these two, the system does.
-
ENQUEUE_<lock object>sets a lock. It writes an entry into the lock table. If a colliding entry already exists, it ends with the exceptionFOREIGN_LOCK. -
DEQUEUE_<lock object>removes a lock.
The parameters that matter most:
| Parameter | Meaning |
|---|---|
The lock argument fields, for example |
The values that say which rows to lock. A field left at its initial value gives a generic lock for that field. |
|
One per lock field. If both the field and |
|
The lock mode for that table: |
|
Who owns the lock and therefore who releases it: 1, 2 or 3 (see the next section). |
|
|
|
|
|
|
ENQUEUE can raise two exceptions. FOREIGN_LOCK means a competing lock exists, and sy-msgv1 holds the name of the user
who holds it. SYSTEM_FAILURE means the lock server reported a problem, and the lock was not set. If the program does not
handle them, the system issues messages itself.
Checking a lock means trying to set it. The Keyword Documentation says that an SAP lock is checked by trying to set a
corresponding lock and handling the exception FOREIGN_LOCK.
Lock a claim before changing it
The scenario: a clerk changes the total of claim C-0001. The program must lock the claim, read it, change it, write it
back, and release the lock. If somebody else holds the lock, the program must say so instead of changing the claim.
Classic ABAP
In classic Standard ABAP the program calls the generated function modules. The listing assumes the lock object EZEXP_CLAIM
described above. It requires an SAP system; not run here.
DATA claim_id TYPE zexp_claim-claim_id VALUE 'C-0001'.
CALL FUNCTION 'ENQUEUE_EZEXP_CLAIM'
EXPORTING
mode_zexp_claim = 'E'
claim_id = claim_id
_scope = '1'
EXCEPTIONS
foreign_lock = 1
system_failure = 2
OTHERS = 3.
CASE sy-subrc.
WHEN 0.
UPDATE zexp_claim SET total_amount = total_amount + 10
WHERE claim_id = @claim_id.
COMMIT WORK.
CALL FUNCTION 'DEQUEUE_EZEXP_CLAIM'
EXPORTING
mode_zexp_claim = 'E'
claim_id = claim_id
_scope = '1'.
WHEN 1.
MESSAGE |Claim { claim_id } is locked by user { sy-msgv1 }.| TYPE 'I'.
WHEN OTHERS.
MESSAGE |The lock server reported a problem.| TYPE 'E'.
ENDCASE.
Source: ABAP Dictionary: Function Modules for Lock Requests and Keyword Documentation: SAP Locks, Set and Release
Reading it: _scope = '1' makes the lock belong to the dialog only, so COMMIT WORK does not remove it and the program
removes it with DEQUEUE. The UPDATE uses ABAP SQL, which is subject to the usual rules of
ABAP SQL: Writing Data; the lock does not change what the
statement does, it only keeps cooperating programs out. A second clerk who runs the same program while the first is between
ENQUEUE and DEQUEUE gets sy-subrc 1 and the message with the first clerk’s user name.
ABAP Cloud
ABAP Cloud does not permit calling the generated function modules directly. The documentation for the ABAP environment says
the calls are wrapped in a generic API, the class CL_ABAP_LOCK_OBJECT_FACTORY. Its method GET_INSTANCE returns an
instance for a lock object, the instance’s method ENQUEUE sets the lock and DEQUEUE releases it, and the factory’s
method DEQUEUE_ALL releases all locks of the current LUW. The interface IF_ABAP_LOCK_OBJECT holds the constants for the
lock modes. The failure case raises CX_ABAP_LOCK_FAILURE; the subclass CX_ABAP_FOREIGN_LOCK, which an SAP sample catches
before the general one, carries the user name as user_name. The listing requires an SAP system; not run here.
DATA claim_id TYPE zexp_claim-claim_id VALUE 'C-0001'.
TRY.
DATA(lock) = cl_abap_lock_object_factory=>get_instance( iv_name = 'EZEXP_CLAIM' ).
CATCH cx_abap_lock_failure INTO DATA(technical_error).
RAISE SHORTDUMP technical_error.
ENDTRY.
TRY.
lock->enqueue( it_parameter = VALUE #( ( name = 'CLAIM_ID'
value = REF #( claim_id ) ) ) ).
UPDATE zexp_claim SET total_amount = total_amount + 10
WHERE claim_id = @claim_id.
lock->dequeue( ).
CATCH cx_abap_foreign_lock INTO DATA(foreign_lock).
DATA(text) = |Claim { claim_id } is locked by user { foreign_lock->user_name }.|.
CATCH cx_abap_lock_failure INTO technical_error.
RAISE SHORTDUMP technical_error.
ENDTRY.
Source: ABAP environment: Lock Objects and the lock method of the unmanaged flight reference scenario, abap-platform-refscen-flight: /DMO/BP_TRAVEL_U
Reading it: the parameter name is the name of the lock parameter, which the Dictionary documentation says is in most cases
the name of the table field, and value is a reference to the value. The sample passes the business key only and not the
client. No lock mode is passed, so the mode stored in the lock object applies; the method enqueue has an it_table_mode
parameter to override it per table. In a real program the dequeue call must also run when the code between enqueue and
dequeue fails, so that the claim is not left locked until the program ends.
How long a lock lives
A lock entry stays until one of these things happens. The point at which it ends depends on the _SCOPE value that set it.
_SCOPE |
Who owns the lock and when it ends |
|---|---|
1 |
The dialog only. Ended by |
2 |
The update only. If |
3 |
Both owners. It ends when the last of the two has released it. |
The two owners are created at the start of an SAP LUW: the dialog owner and the update owner. The _SCOPE parameter belongs
to the operation, not to the lock, so calling ENQUEUE again with _SCOPE 2 on a lock that has the dialog as its owner
adds the update as a second owner, which gives the same result as a single call with 3. DEQUEUE can release a lock
independently of the update only when its _SCOPE is greater than or equal to the value the ENQUEUE used.
The system also removes all locks of a program at the end of the program or transaction, which the documentation calls an
implicit DEQUEUE_ALL.
Locks handed to the update system are also saved in a backup file as well as the lock table, so they are not lost if the enqueue server fails.
The enqueue server and the lock table
Lock entries are not kept in the database. The SAP Lock Concept page says the lock concept is implemented by the Standalone Enqueue Server 2, and the Lock Table page says the lock table is a table in the main memory of that server. The Keyword Documentation describes the same thing from the program’s side: the lock function modules access a central lock table, every AS ABAP contains exactly one such table, and an enqueue function module sets a lock by writing an entry in it.
Each request is checked against the table. If a colliding lock exists, the request is rejected, otherwise a new entry is written. A lock operation takes a few milliseconds.
The lock table has one entry per lock. Its columns include the lock timestamp, the client, the user name, the lock mode (S, O, E or X), the dialog and update counters for cumulated locks, a backup flag, the table name and the lock argument, which can contain wildcards.
To see the entries, the Keyword Documentation names transaction SM12 for the table of locks, and the platform documentation for the Standalone Enqueue Server 2 names SMENQ for analysing the lock table. A transaction here means a screen started by a short code in SAP GUI. Both are SAP GUI tools of classic systems; this page does not describe a way to list lock entries in the ABAP environment.
The diagram shows the order of events for the claim in the earlier listings. Clerk B is not stopped by the database but by the entry that A wrote: the server compares table name, lock argument and mode and, because E collides with E, rejects B’s request.
Locking in RAP
In a RAP business object you do not call ENQUEUE yourself in the ordinary case. The RAP guide calls the mechanism
pessimistic concurrency control: a data set that one user is changing cannot be changed by another user at the same time.
Technically it uses the same enqueue locks and the same global lock table described above. Before data is changed, the data
set gets an entry in the lock table, a second request is rejected, and the entry is removed after the change has been
executed successfully.
The locking structure of a business object is written in its behavior definition with two keywords:
define behavior for ZI_ExpClaim alias Claim
implementation in class zbp_i_expclaim unique
lock master
{
association _Items { create; }
}
define behavior for ZI_ExpItem alias Item
implementation in class zbp_i_expitem unique
lock dependent by _Claim
{
association _Claim;
}
The listing requires an SAP system; not run here. It is a cut-down sketch for the claim and its items: the full behavior
definition has more entries, and the CDS views ZI_ExpClaim and ZI_ExpItem are the subject of later pages. What the lines
mean, from the Keyword Documentation:
-
lock mastermarks the root entity. Currently only root entities can be lock masters, and every business object that supports locking must have at least one. -
lock dependent by _Claimmarks a child entity. Lock requests for the child are delegated to its lock master, found through the association_Claim, which must be declared in the behavior definition and also exist in the underlying CDS data model. -
Whenever one entity instance is locked, its lock master instance and all dependent instances are locked for editing by someone else. If one item of claim
C-0001is being edited, all items of that claim are locked, but the items of claimC-0002are not. -
The lock is set implicitly when the instance is changed by an update, a delete, a create by association or an action. A plain create does not lock, because there is no instance yet, so the lock does not prevent two users creating the same key; a managed business object runs a uniqueness check for that, an unmanaged one has to code it.
-
The lock mechanism is defined in the interface behavior definition, not in the projection.
Managed and unmanaged business objects
In a managed business object the framework does the locking and nothing is implemented in the behavior pool. The lock
definition is always part of the behavior definition template. If you add the keyword unmanaged after lock master, you
write the lock yourself.
In an unmanaged business object, or a managed one with an unmanaged lock, you implement the handler method FOR LOCK in the
behavior pool. The runtime calls it before every change; it receives the keys of the instances to lock, and it calls the
enqueue method of a lock object for each of them. If the lock fails it fills the response parameters failed and
reported, which is how the user sees the message. The SAP unmanaged flight scenario does exactly that:
CLASS lhc_claim DEFINITION INHERITING FROM cl_abap_behavior_handler.
PRIVATE SECTION.
METHODS lock FOR LOCK
IMPORTING keys FOR LOCK Claim.
ENDCLASS.
CLASS lhc_claim IMPLEMENTATION.
METHOD lock.
TRY.
DATA(lock) = cl_abap_lock_object_factory=>get_instance( iv_name = 'EZEXP_CLAIM' ).
CATCH cx_abap_lock_failure INTO DATA(technical_error).
RAISE SHORTDUMP technical_error.
ENDTRY.
LOOP AT keys ASSIGNING FIELD-SYMBOL(<key>).
TRY.
lock->enqueue( it_parameter = VALUE #( ( name = 'CLAIM_ID'
value = REF #( <key>-ClaimId ) ) ) ).
CATCH cx_abap_foreign_lock.
APPEND VALUE #( %tky = <key>-%tky ) TO failed-claim.
CATCH cx_abap_lock_failure INTO technical_error.
RAISE SHORTDUMP technical_error.
ENDTRY.
ENDLOOP.
ENDMETHOD.
ENDCLASS.
Source: RAP: Implementing the LOCK Operation and Keyword Documentation: FOR LOCK, RAP Handler Method
The listing requires an SAP system; not run here. The method shape (FOR LOCK, the importing keys, the response
parameter failed) is from the handler-method topic; the key field ClaimId and the entity alias Claim are those of this
page’s sketch. A complete implementation also fills reported with a message, as the SAP sample does with a message class.
During the save sequence the lock is removed in the cleanup method after the data has been saved successfully.
Locks and drafts
When a draft is created for an active instance, the active instance receives an exclusive lock that survives the end of the ABAP session. After a configured time that exclusive lock expires and an optimistic phase begins, in which another user may change the active instance directly, which invalidates the draft. The draft is removed when its owner discards it, when it lapses (by default the life-cycle service discards an unused draft after 28 days), when the active instance is changed directly, or when a second draft is created; if the owner resumes it, a new exclusive lock is set. This is why a RAP application that supports drafts needs no input from the clerk to avoid lost updates, and why the lifetime of the lock in a draft scenario is not tied to the LUW or the session.
Common mistakes
-
Reading a record without a lock and assuming nobody else is changing it: reading is not blocked, and the Keyword Documentation example says all users can still access locked records with ABAP SQL if the program does not check the lock.
-
Forgetting that the lock belongs to the cooperating programs: a report that updates the table directly ignores the lock.
-
Using
_SCOPE2 in a program that does not use an update task: the lock then has nobody to release it until the program ends. -
Passing a different mode to
DEQUEUEthan toENQUEUE: the lock is not removed. -
Putting a wildcard character, the at sign, in a key value by accident: it is a wildcard in lock arguments, so the lock becomes generic. Replace it before the call.
-
Transporting the function group that holds the generated function modules instead of the lock object.
Summary
-
A lock object in the ABAP Dictionary defines which tables and key fields an SAP lock covers; activating it generates the function modules
ENQUEUE_<name>andDEQUEUE_<name>. -
The lock modes are S (shared), E (exclusive), X (exclusive, not cumulative) and O (optimistic); two locks collide when they cover the same data and at least one of them is not in mode S.
-
The enqueue server keeps the lock entries in the lock table in memory, not in the database, and a lock is only respected by programs that also ask for it.
-
_SCOPEdecides who releases a lock: the dialog, the update, or both;FOREIGN_LOCKorCX_ABAP_FOREIGN_LOCKis the answer when somebody else holds it. -
Classic code calls the function modules, ABAP Cloud code uses
CL_ABAP_LOCK_OBJECT_FACTORY, and RAP does it for you withlock masterandlock dependent by, unless an unmanaged lock requires the methodFOR LOCK.