Platinum Partner
java,opinion,concurrency,performance,threading

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.

Published at DZone with permission of {{ articles[0].authors[0].realName }}, DZone MVB. (source)

Opinions expressed by DZone contributors are their own.

{{ tag }}, {{tag}},

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}
{{ parent.authors[0].realName || parent.author}}

{{ parent.authors[0].tagline || parent.tagline }}

{{ parent.views }} ViewsClicks
Tweet

{{parent.nComments}}