Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

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

DZone's Guide to

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

· Performance Zone
Free Resource

Download our Introduction to API Performance Testing and learn why testing your API is just as important as testing your website, and how to start today.

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

Find scaling and performance issues before your customers do with our Introduction to High-Capacity Load Testing guide.

Topics:

Published at DZone with permission of Peter Lawrey, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

THE DZONE NEWSLETTER

Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

X

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

{{ parent.tldr }}

{{ parent.urlSource.name }}