B4J Question lock.WriteLock / WriteRelease

aaronk

Well-Known Member
Licensed User
Longtime User
Hi,

Looking through the CloudKVS tutorial and I think this might be good for a project I am working on at the minute.

I was looking through the code for the server for the CloudKVS, and come across the 'AddItem' sub in the DB module.

Just wondering what does lock.WriteLock do ?

I noticed that lock.WriteRelease is called at the end of the sub so I am guessing it locks the sub while it runs the sub or does it do something else ?
 

Erel

B4X founder
Staff member
Licensed User
Longtime User
jBuilderUtils is a small library with two types:
ReadWriteLock and AtomicInteger.

AtomicInteger is a simple counter that can be accessed from multiple timers.
ReadWriteLock: https://en.wikipedia.org/wiki/Readers–writer_lock
In the case of CloudKVS, only the write lock is used. Only one thread can enter the code protected with this lock.

The AddItem sub, first calculates the current maximum id and then inserts the item with id + 1. The operation must be atomic. The database cannot be modified in the middle.

I don't recommend using the ReadWriteLock unless you understand the server threading model. In most cases it is not required. Using locks incorrectly can easily hang to server.
Two simple solutions:

1. Use a single threaded servlet.
2. Use CallSubDelayed to call a code module. The code will run on the main thread.
 
Upvote 0
Top