Search code examples
javamultithreadingakkavolatile

Is the volatile keyword required for "non-concurrent multithreading"?


I have an object which is used by multiple threads, but never concurrently (always only one thread executes a method on it). It contains several non-final fields. Now I am wondering whether I have to mark all fields as volatile to ensure that the next thread (which might have used the object before) will see the changes. Without volatile, at what point does a thread pick up changes from another thread? Are there any guarantees?

If I have to use volatile, how does Akka solve this problem?

Behind the scenes Akka will run sets of actors on sets of real threads, where typically many actors share one thread, and subsequent invocations of one actor may end up being processed on different threads. Akka ensures that this implementation detail does not affect the single-threadedness of handling the actor’s state.


Solution

  • There is no need to make the member variables volatile, if the happens-before relationship is established outside the object. A happens-before relationship can be established even without a synchronized block. The following example uses a volatile for that purpose -- guaranteeing that a writer and a reader can not access the same object at the same time. In this case it is guaranteed that the reader will read the correct value.

    class Foobar {
        public static volatile Foobar instance = new Foobar(42);
        public int value;
        public Foobar(int value) { this.value = value; }
    }
    
    int reader() {
        return Foobar.instance.value;
    }
    
    void writer(int value) {
        Foobar.instance = new Foobar(value);
    }
    

    So, the interesting part is the code outside the object - guaranteeing that only one thread has access to the object. It is possible to write code that guarantees it without establishing a happens-before relationship. However, it would be strange, and you should fix the problem there, instead of making the member variable volatile.