Over a million developers have joined DZone.
Platinum Partner

Is it Better to use Immutable or Mutable Values in Multi-threaded Systems

· Performance Zone

The Performance Zone is brought to you in partnership with New Relic. Quickly learn how to use Docker and containers in general to create packaged images for easy management, testing, and deployment of software.

@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.

The Performance Zone is brought to you in partnership with New Relic. Read more about providing a framework that gets you started on the right path to move your IT services to cloud computing, and give you an understanding as to why certain applications should not move to the cloud.

Topics:

Published at DZone with permission of Peter Lawrey , DZone MVB .

Opinions expressed by DZone contributors are their own.

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

{{ parent.tldr }}

{{ parent.urlSource.name }}