The SYNC statement marks a statement block as a critical section by obtaining the mutual-exclusion lock for a given object, executing a block of statements, and then releasing the lock.
General Format
Syntax Rules
- identifier-1 must be a reference type.
General Rules
- identifier-1 specifies the object that you want to lock on. Typically,
identifier-1 is the SELF keyword if you want to protect an instance variable, or a type if you want to protect a static variable (or if the critical section occurs in a static method in the given class).
-
statement- block-1
represents the statements of the critical section.
- When the object is locked, code executing in the same execution thread can also obtain and release the lock. However, code executing in other threads cannot. It is blocked until the lock is released.
Example
In the following example, the SYNC statement locks a set of critical statements.
method-id Withdraw.
procedure division using by value amount as binary-long
returning ret as binary-long.
sync on self
if balance >= amount
display "In critical section"
compute balance = balance - amount
set ret to amount
else
display "In critical section"
set ret to 0
end-if
end-sync
end method.