Closing via java.util.concurrent.ConcurrentHashMap in the receiving method of the Future of Actor?
I have an actor where I want to store my mutable state inside a map.
Clients can send messages Get(key:String)
and Put(key:String,value:String)
this member.
I am considering the following options.
- Don't use futures inside the Actor's takeover method. This can have a negative impact on both latency and throughput if I have a large number
gets/puts
, because all operations will be done in order. - Use
java.util.concurrent.ConcurrentHashMap
and then call get and put elements insideFuture
.
Considering what java.util.concurrent.ConcurrentHashMap
is thread safe and the providers of finer granularity, I was wondering if it is worth closing via concurrentHashMap inside the Future created for each put and get.
I know this is a really bad idea to close a more volatile state inside the Future inside the Actor, but I'm still curious to know if this is correct in this case or not?
source to share
In general, it java.util.concurrent.ConcurrentHashMap
is performed for simultaneous use. As long as you are not trying to transfer the closure to another machine and you think the consequences of using it at the same time (for example, if you are reading a value, use a function to change it and then revert back, you want to use a method replace(key, oldValue, newValue)
to make sure it is not changed during processing?), that should be fine in Futures.
source to share
Maybe a little late, but still in the book Reactive Web Applications, the author pointed out indirectly to this particular issue using pipeTo as shown below.
def receive = {
case ComputeReach(tweetId) =>
fetchRetweets(tweetId, sender()) pipeTo self
case fetchedRetweets: FetchedRetweets =>
followerCountsByRetweet += fetchedRetweets -> List.empty
fetchedRetweets.retweets.foreach { rt =>
userFollowersCounter ! FetchFollowerCount(
fetchedRetweets.tweetId, rt.user
)
}
...
}
where followerCountsByRetweet
is the mutable state of the actor. The result fetchRetweets()
, which is the Future, is passed to the same actor as the message FetchedRetweets
, which then acts on the message to change the state of acto. This will reduce any concurrent operation in the state
source to share