score:1

Accepted answer

the problem of parallel access to the same data structure is twofold. first, we need to serialize parallel updates. @tim gave a comprehensive answer to this. second, in the case there are many readers, we may want to allow them to read in parallel with writing. and in this case immutability plays its role. without it, writers have to wait the readers to finish.

score:0

you may use cats ref type class https://typelevel.org/cats-effect/concurrency/ref.html but it is that atomicreference realization, or write some java.util.concurent.concurenthashmap wrapper

score:1

there isn't really a "functional" way to have a data structure that can be updated by multiple threads. in fact one reason that functional programming is so good in a multi-threaded environment is because there aren't any shared data structures like this.

however in the real world this problem comes up all the time, so you need some way to serialise access to the shared data structure. the most crude way is simply to put a big lock around the whole code and only allow one thread to run at once (e.g. with a mutex). with clever design this can be made reasonably efficient, but it can be difficult to get right and complicated to maintain.

a more sophisticated approach is to have a thread-safe queue of requests to your data structure and a single worker thread that processes these requests one-by-one. one popular framework that supports this model is akka actors. you wrap your data structure in an actor which then receives requests to read or modify the data structure. the akka framework will ensure that only one message is processed at once.

in your case your the actor would manage the heap and receive updates from the stream which would go into the heap. other threads can then make requests that will be processes in a sequential, thread-safe way. it is best if these request perform specific queries on the heap, rather than just returning the whole heap every time.


Related Query

More Query from same tag