B4J Question Server threading

wl

Well-Known Member
Licensed User
Longtime User
I just can't seem to understand how threading works in B4J.

A server class instance runs in its own thread ... When I call a method of a global class instance (like the chat shared in the example) inside a server class instance: does this run on the main thread on within the thread of the server class instance ?

A server also allows to create a threadsafe map (CreateThreadSafeMap)... But what happens in this example (in consecutive order)

1. Server class instance A checks whether key X exists
2. Server class instance B checks whether key X exists
3. Server class instance A sees the key does dot exist and it adds a key
4. Server class instance B also came to the conclusions the key did not exist (step 2) and wants to add it as well
--> error because meanwhile the key was already created.

So I understand the Map could work threadsafe internally but I would assume I still need something like a critical section/semaphore to protect code in a class (where step 1 & 3 on one side and 2 & 4 on the other would be protected) ?

Thanks
 
Last edited:

billzhan

Active Member
Licensed User
Longtime User
Do you mean chatshared module in Chatroom example? chatshared is a code module (not a class) which singleton. It runs in the thread where it's been called.
http://www.b4x.com/android/fo...l-for-basic4android-developers.34659/#content

B4X:
CreateThreadSafeMap As Map
Returns an initialized Map that can safely be accessed by multiple threads (based on Java ConcurrentHashMap).
Unlike the standard Map the order of items is not preserved.
Note that this Map does not support the following methods: GetKeyAt and GetValueAt.

I think the it's intended for multiple threads access ( and not to cause exceptions ), it doesn't ensure the order (A B). It can be used like a map.

You need the check X key in a single thread. CallSubDelayed/CallSubDelayed2 are used in the Chatroom example to ensure that the sub runs in a single thread ( main module )

You should have read the following threads and replies:
https://b4x.com/android/forum/threads/webapp-chatroom-threads-sessions-and-server-events.39969/
 
Upvote 0

wl

Well-Known Member
Licensed User
Longtime User
Thanks !

Indeed, the ChatShared is a module, I missed that ...

Issue is that I have something similar but there the code is encapsulated in a class which would not run at the main thread.
 
Upvote 0
Top