Should fields be explicitly final in order to have a “correct” immutable object?

You often read about immutable objects that require leaf fields to be immutable in Java. Is this true, or is it just enough not to have universally accessible variability and not actually mutate the state?

For example, if you have an immutable object built by the builder’s template, you can do this if the builder assigns separate fields as they are assembled or has a constructor that holds the fields themselves and ultimately returns an immutable object, passing values ​​for it (private) constructor.

The presence of final fields has the obvious advantage of preventing implementation errors (for example, allowing the code to save the link to the builder and "build" the object several times, while mutating the existing object), but having the Builder to store its data inside the object as it is created looks like DRYer.

So, the question is this: Assuming that Builder does not skip the object earlier and stops modifying the object ever built (for example, setting its reference to the object as zero), something actually happened (for example, improved thread safety) in the "immutability" of the object, if the fields of the object were made final instead?

+5
source share
5 answers

, " " final. , , final , . volatile, & hellip; , , , "" "".

final . , . , , , Project Lombok . IDE, , , .

+6

, , - . , , , . , , , .

, , "" . - .

Clojure, , , , , , . .

- , , , , . , .

+2

, , , , , .

, POST- - -, bean.

0
source

You can definitely have an immutable object with not the last fields.

For example, see java 1.6 implementation of java.lang.String.

0
source

Comment: @erickson

Like:

class X {volatile int i, j; }
X y

// thread A: 
X x = new X;
xi = 1;
xj = 2;
y = x;

// thread B: 
if (y! = null) {
    a = yi; 
    b = yj;
}

?

0
source

All Articles