When embedding threads, is it better to use immutable objects over mutable ones?

I am currently studying threads in java, and from what I read, their implementation is not a problem, as it makes your code stream safe. This brings me to my question: should immutable objects ever be used to prevent concurrency errors?

I read different opinions about when to use mutable objects, including:

If immutable objects are good, why do people keep creating mutable objects? (Programmers.SE)

for large and / or complex objects, creating a new copy of the object for each individual change can be very expensive and / or tedious. And for objects with a clear identity, changing existing objects is much simpler and more intuitive than creating a new, modified copy.

Immutable Objects (Java Tutorials)

The impact of creating an object is often overestimated and can be offset by some efficiency associated with immutable objects. These include reducing overhead due to garbage collection and eliminating the code needed to protect volatile objects from corruption.

So, is there any best practice when implementing threads? Should I always try to use immutable objects whenever possible?

+4
4

( , ) , , , , ; , , . , , Object Object, (String, , Guava Immutable*).

, , , , , - , .

, - , final, . , , abstract, final, final .

+3

, .

:

  • THREADSAFE. , , .

  • . , synchronized. .

  • singleton. , . , , , .

+1

, , . , ? ?

, , , . , ...

, ACID: http://en.wikipedia.org/wiki/ACID

, Java , . , , , , . , - ?

0

; , , . (, , .)

- , , , . , , , , , .

0

All Articles