Hi everyone, I don't know if this is the correct c...
# kotlin-native
m
Hi everyone, I don't know if this is the correct channel. I'm working on a kmm project (Kotlin 1.7.0, kotlin.native.binary.memoryModel=experimental) and I have an IPWebSocket class.
Copy code
class IPWebSocket() {//...
	private val requestQueue: MutableList<IPMessageRequest> = mutableListOf()
	//...

	fun send(request: IPMessageRequest) {
		requestQueue.add(request)
		webSocket.sendMessage(request)
		scope.launch {
            delay(REQUEST_TIMEOUT)
            requestQueue.firstOrNull { it == request }?.let {
                //Some operations
            }
        }
	}
	//...
	fun receive(msg: Message) {
		val iterator = requestQueue.listIterator()
        while (iterator.hasNext()) {
            val request = iterator.next()
            if (msg.msgid == request.msgid) {
                iterator.remove()
            }
        }
	}
}
With the new Native Memory Management, by reading the docs, I understood that I don't need to handle locks on the requestQueue like I was doing before with stately-iso-collection but I'm still getting ConcurrentModificationException on the send function. What I am doing wrong? Note: obviously the send and receive methods can be accessed by multiple threads EDIT: ok I think I found the problem, we're using kotlin.coroutines "1.6.0-native-mt" and -native-mt should be removed. But I think the app will slow down If I do that.
m
The new memory model doesn't just make things thread safe, instead it makes it so you no longer get an exception when trying to share state. You still have to share the state safely or you get incorrect behavior. If you are going to access a list from multiple threads, you must add some sort of synchronization around the access.
m
@mkrussel thank you, I was thinking the same. What is the best solution to synchronize access in a kmm project?
m
There's several ways. There's using thread isolation (what stately did). There's using synchronization blocks, locks, or mutexs.
So far, I've stuck with the avoid sharing mutable state across threads.
m
Very clear, thank you very much
p
Give it a chance to the actor model or a simplified version using a request queue to access a resource.
In regards to the edited answer, why not using the native-mt version will be slow?