Question

I'm using slick to store data in database, and there I use the threadLocalSession to store the sessions.

The repositories are used to do the crud, and I have an Akka service layer that access the slick repositories.

I found this link, where Adam Gent asks something near what I'm asking here: Akka and Java libraries that use ThreadLocals

My concern is about how does akka process a message, as I store the database session in a threadLocal, can I have two messages been processed at the same time in the same thread?

Let's say: Two add user messages (A and B) sent to the userservice, and message A is partially processed, and stopped, thread B start to process in the same thread that thread A has started to process, which will have the session stored in it's localSession?

Was it helpful?

Solution

Each actor processes its messages one at a time, in the order it received them*. Therefore, if you send messages A, B to the same actor, then they are never processed concurrently (of course the situation is different if you send each of the messages to different actors).

The problem with the use of ThreadLocals is that in general it is not guaranteed that an actor processes each of its messages on the same thread.

So if you send a message M1 and then a message M2 to actor A, it is guaranteed that M1 is processed before M2. What is not guaranteed that M2 is processed on the same thread as M1.

In general, you should avoid using ThreadLocals, as the whole point of actors is that they are a unit of consistency, and you are safe to modify their internal state via message passing. If you really need more control on the threads which execute the processing of messages, look into the documentation of dispatchers: http://doc.akka.io/docs/akka/2.1.0/java/dispatchers.html


*Except if you change their mailbox implementation, but that's a non-default behavior.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top