In MuleSoft applications running in multi-threaded or multi-worker environments, the risk of parallel writing issues arises when multiple threads or workers attempt to access or update the same shared resource simultaneously. These issues can lead to data corruption, inconsistencies, or unexpected behavior, especially in distributed systems where Mule applications are deployed across multiple workers in a cluster.
The Problem: Parallel Writing
Let me illustrate the problem first. I created a simple counter application that supports /inc
and /get
operations. The /inc
operation increases the counter by 1, and the /get
operation returns the current value.
Now, if I hit /inc parallelly from JMeter 300 times, the /get
should return exactly 300 if all writes are successful and no overwrite happens. However, in Mule4, we will not get 300.
Issue: Lower Count Due to Overwriting
The screenshot shows we are getting a much lower number here because of parallel threads, which results in overwriting.
The Solution: Distributed Locking in Mule 4
To solve this issue, Mule 3 provided the “retrieve-with-lock” object store operation (<objectstore:retrieve-with-lock>
). However, Mule 4 does not offer this out-of-the-box solution. Instead, Mule 4 requires distributed locking via LockFactory.createLock()
.
The counter application version 2 uses a Groovy script and Java bean to implement distributed locking. The Groovy script is very small, and it performs only the bean lookup and method invocation: