Transaction Lock example

When embedded as part of a larger mix, a lock service enables operations which might otherwise occur simultaneously in different transactions to be serialized until the whole transaction is completed.

Figure: Transaction Lock - Mix overview


Tip: Get the code from the SPARKL public repository.
Table 1. Transaction Lock - Markup
Example Description
<folder name="LockExample">  
  <service name="Expr"    
    provision="expr">    
    <prop name="expr.state"      
      IsLocked="NewIsLocked"/>    
    <prop name="expr.src"      
      content-type="text/x-erlang"><![CDATA[
NewIsLocked = false.    
    ]]></prop>  
  </service>  
  <field name="GET_LOCK"/>  
  <field name="LOCK"/>  
  <field name="UNLOCK"/>  
  <field name="error"    
    type="string"/>   

  <mix name="Mix">    
    <request name="Lock"      
      service="Expr"      
      fields="GET_LOCK">      
      <prop name="expr.bind.out"        
        Error="error"/>      
      <prop name="expr.src"        
        content-type="text/x-erlang"><![CDATA[
case IsLocked of  
  true ->    
    Error = "Already locked",    
    "Error";   

  false ->    
    NewIsLocked = true,    
    "Ok"
end.      
      ]]></prop>      
      <reply name="Ok"        
        fields="LOCK"/>      
      <reply name="Error"        
        fields="error"/>    
    </request>    
    <consume name="Unlock"      
      service="Expr"      
      fields="UNLOCK">      
      <prop name="expr.src"        
        content-type="text/x-erlang"><![CDATA[
NewIsLocked = false.      
      ]]></prop>    
    </consume>  
  </mix>
</folder>
To use the lock service:
  • Specify the field LOCK in the request or consume fields for any given operation
  • Specify the condition under which the unlock occurs in a consume operation

The service property expr.state declares that:

  • IsLocked is a state variable
  • The NewIsLocked variable is used to update it in an operation script

The IsLocked variable is initialised to false, that is, the service is not locked to start with.

Note: The variable can be initialised with the expr.init property too. It does not count as a state change.

The Lock request is used to obtain the lock.

Two replies are possible:

  • Ok, the LOCK field is output
  • Error, an error message is sent

The error field is specified in the expr.bind.out property of the request operation.

The consume Unlock is used to open the lock. It sets the NewIsLocked variable to false.

Note: Do not manually type the <![CDATA...]]> delimiters. The Editor automatically renders text content as XML CDATA sections.