Concurrent Access to Map

What is a good way to deal with concurrent access to a map, shared by multiple threads? I found [0] mentioning a wrap for a ConcurrentHashMap, but I am interested in functional style in achieving this. Any suggestions?

Thanks

[0]. https://stackoverflow.com/questions/18660769/best-practices-for-mixing-in-scala-concurrent-map

If you’re dealing with a shared, mutable data structure you’ve kind of left the realm of things for which there’s a functional solution in the general, I think. Shared mutability precludes anything being truly functional because affecting shared state becomes a requirement.

That said, there are ways you could model this that might or might not work depending on the specifics of your situation. You could, for example, encapsulate access to the mutability somehow. Then the components that maintain the state are at least separated from the components that process the state.

There are other solutions too, but it’s kind of difficult for me to know what to suggest without any specifics.

My use case is I have a file monitor that watches files, storing those files as custom objects in Map[Path, MyObject](). When any of files are updated, it will update Map accordingly. Meanwhile multiple threads will have access to Map, checking if corresponded Path exists or not, then perform necessary operations such as obtaining the object and then executing some methods and so on. My naive thought is marking Map with volatile keyword. For instance,

@volatile var map = Map.empty[Path, MyObject]

otherwise to synchronize the check-then-action operation code block.

However I am not sure if that’s enough. In addition I prefer functional style so I would like to check if there exists better or correct way to do it.

Thanks

Sometimes the Java standard library has a solution that’s good enough. I’d say a concurrent map is one of these cases: https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/ConcurrentMap.html

The synchronised access patterns you’re describing are already implemented there.

Yes currently that’s what I use to implement my solution. But I would like to learn functional style if there exists such solution.

Thanks