Is it better to use immutable or mutable values in multi-threaded systems

@martypitt asked an interesting question which I think deserved it's own post.

Most of the articles I've read of yours focus on concurrency and/or high performance. Most books I've read on concurrency espouse the benefits of immutability.

If you have data shared between threads, it is a lot easier to write and debug if the data uses immutable values. i.e. you might have a mutable collection, or queue, but the data you hold in it is immutable. This is where Date could be a problem as it is mutable though it is rarely used this way. It can be treated as immutable, not by good design but by the fact most people don't use the setTime() method.

Mutliple Actors

My preference is to use the actor pattern and have a series of single threaded "engines" which send messages to each other via systems such as Chronicle. In this model, each thread has most data local to a thread and mutable. The benefit of using mutable state is the code is simpler (you are effectively writing single threaded code), it produces far less garbage, and in extreme cases, you can have systems which GC less than once per day (which is the goal of the projects I work on) BY less than once per day, I include minor collections as well. 

Using mutable state in one thread, you write simple, single threaded code, you don't need to worry about locking, you can minimise GCs, and each thread can run as independently as possible.


  1. Do you use immutable messages between such single-threaded engines?

  2. They are effectively immutable i.e. write once only. This is not enforced, but I would recommend you do that.

    Note: the exception is that in each message is a timestamp for the writer and the reader thread. This gives you write to read delays accurately but doesn't follow the "immutable" message model as such.


Post a Comment

Popular posts from this blog

Java is Very Fast, If You Don’t Create Many Objects

System wide unique nanosecond timestamps

Comparing Approaches to Durability in Low Latency Messaging Queues