#1332 Actors and shared repositories

Henri Fri 26 Nov 2010

I'm pretty new to Fantom and very new to the concept of Actors. I'm fumbling with the following issue.

In Java, I use shared in-memory object repositories where reads are frequent and writes (add, update, remove) are infrequent. I use an immutable HashMap internally, where the add, update and remove methods use a copy-on-write strategy. The result is that only these write methods need to be synchronized (on an internal lock object), and read methods do not require any synchronization at all.

Now I want to do something similar in Fantom. However, I have no clue where to start. I can't share the mutable repository with multiple Actors. I suppose I could use a single Actor to do the writes, but how can I then make the copy-on-write action atomic? Also, isn't it very inefficient to switch threads (Actors) on every write?

brian Sat 27 Nov 2010

Depending on how exactly you manage your map, how big, how often it changes you have two choices:

The first is to use AtomicRef and store an immutable version of Map.toImmutable. This will be really efficient for reads, but does require a full copy-on-write for each change. And you still only want one Actor to be responsible for writes to avoid race conditions.

Using an Actor you would wrap get/set in messages to the actor, and store the mutable state in actors. This design is more scalable at the expense of context switching on each read. But since the mutable state is accessible by only one thread it is thread safe (read/writes will be processed serially as messages). I use this design as the fundamental of our commercial database and it works extremely well with millions of key/value pairs. The trick is that you can't iterate in the traditional way - in my case what I do is accept filters to the actor which returns matches as lists.

Login or Signup to reply.