The Road to Immutability
Effective and eventual immutability with maddi, a static code analyzer for Java.
Concepts
- Concepts
- 1. Introduction
- 2. Final fields
- 3. Modification
- 4. Containers
- 5. Dependence
- 6. Immutability
- 7. Ownership
- 8. Eventual immutability
- 9. Modification, part 2
- 10. More on hidden content
- 11. Nullability
- Under the hood
- In practice
1. Introduction
This document aims to be a logical walk through of the concepts of the maddi project. It does not intend to be complete, and is not structured for reference.
The overarching aim of the maddi project is to improve everyday programming by making code more readable, more robust, and more future-proof. Concretely, the project focuses on adding various forms of immutability protections to your Java code base, by making the (im)mutable nature of the types more visible.
Why Java? As a widely used object-oriented programming language, it has evolved over the years, and it has been increasingly equipped with functional programming machinery. It is therefore possible to write Java code in different styles, from overly object-oriented to almost fully functional. Combine this with lots of legacy code, both in house and in libraries, and many large software projects will end up mixing styles a lot. This adds to the complexity of understanding and maintaining the code base.
Why immutability? An important aspect of understanding the code of large software projects is to try to assess the object lifecycle of the data it manages: when and how are these objects modified? In object-oriented programming, full of public getters and setters, objects can be modified all the time. In many a functional set-up, objects are immutable but new immutable versions pop up all the time. Java allows for the whole scale from object-oriented to functional, and the whole ecosystem reflects this choice.
An easy way to envisage the life cycle of an object is to assume that it consists of a building phase, followed by an immutable phase. We set out to show that there are different forms of immutability, from very strict deep immutability to weak guarantees of non-modification, that can be made visible in the code. We believe that code complexity can be greatly reduced when the software engineer is permanently aware of the modification state of objects.
Immutability is the answer to one question about an object: who can modify it?
To answer it, we will have to follow objects as they flow through the program, from parameters into fields, and from fields into return values; we call this linking.
Knowing where objects flow answers two other questions as well: who holds an object, the subject of the chapter on Ownership, and where can null turn up, the subject of the chapter on Nullability.
Both matter in Java, and both become unavoidable when a Java program is translated into a language that has ownership (Rust) or nullability (Kotlin, C#) in its type system.
The maddi project consists of a set of definitions, a static code analyzer to compute and enforce rules and definitions, and IDE support to visualize the results without cluttering. Using maddi in your project will help to maintain higher coding standards, the ultimate beneficiary being code that will survive longer.
A lack of references to academic literature in this version of the document is explained by the fact that this is my first foray into the world of static code analyzers, and theory of software engineering and programming languages. Academically coming from the theory of machine learning, I spent two decades writing software and managing teams of software engineers. This work builds on that practical experience alone. I did not consult or research the literature, and I realize I may be duplicating quite a lot here.
1.1. How the concepts build on each other
The first part of this document is meant to be read in order; every chapter needs the ones before it.
| Chapter | Introduces | Builds on |
|---|---|---|
fields that are not assigned after construction | ||
methods, parameters and fields that change an object graph | ||
types that do not modify what they are given | modification of parameters | |
objects that share a part, so that a modification of one is seen in the other; accessible and hidden content | modification, which travels along links | |
four rules: final fields, unmodified fields, and no exposure through fields, parameters or return values | final fields (rule 0), modification (rule 1), independence (rules 2 and 3) | |
objects with a single holder; finalizers | linking, read as 'who holds' instead of 'who can modify' | |
types that become immutable after a transition | immutability, and finalizers and ownership for the phase before the transition | |
how dependence is computed; modification of hidden content, and how it travels through functional interfaces | all of the above | |
where | linking, with |
The second part describes how the analyzer computes all this, and The analyzer today lists where it currently stands with respect to the definitions. The third part shows the concepts at work.
1.2. Assumptions
We discuss the Java language, version 17 and higher. We have already indicated that we believe that Java offers too much freedom to programmers. In this section, we impose some limits that are not critical to the substance of the discussion, but facilitate reasoning. Think of them as low-hanging fruit programming guidelines:
Exceptions do not belong to the normal programming flow; they are meant to raise situations that the program does not want to deal with.
Parameters of a method cannot be assigned to; we act as if they always have the
finalmodifier. The simple way around is to create a new local variable, and assign the parameter to it.We make no distinction between the various non-private access modifiers (package-private, protected, public). Either a field, method or type (the collective noun for class, interface, record, …) is private, or it is not.
Synchronization is orthogonal to the data flow of the program; whilst it may have an influence on when certain code runs, it should not be used to influence the semantics of the code.
The maddi code analyzer warns for many other doubtful practices, as detailed in the user manual.
1.3. The purpose of annotations
In this document we will add many annotations to the code fragments shown. We are acutely aware annotations may clutter the code and can make it less readable. Some IDEs, however, like JetBrains' IntelliJ IDEA, have extensive support to make working with annotations visually pleasing.
The maddi code analyzer computes almost all the annotations that we add to the code fragments in this document. The complementary IDE plugin uses them to color code types, methods and fields. Except when the annotations act as a contract, in interfaces, they do not have to be present in your code.
Explicitly adding the annotations to classes can be helpful during software development, however. Say you intend for a class to be immutable, then you can add the corresponding annotation to the type. Each time the code analyzer runs, and the computation finds the type is not immutable, it will raise an error.
Explicit annotations also act as a safe-guard against the changing of semantics by overriding methods.
Making the method final, or the type final, merely prohibits overriding, which is typically too strong a mechanism.
The final situation where explicit annotations in the code are important, is for the development of the analyzer. We add them to the code as a means of verification: the analyzer will check if it generates the same annotation at that location.
2. Final fields
Let us start with a definition:
The analyzer annotates with @Final in the latter case; there is no point in cluttering with an annotation when the
modifier is already there.
Fields that are not effectively final are called variable, they can optionally be annotated with @Final(absent=true) .
This definition allows effectively final fields to be assigned in methods accessible only from the constructor:
final modifierclass EffectivelyFinal1 {
@Final
private Random random;
public EffectivelyFinal1() {
initialize(3L);
}
private void initialize(long seed) {
random = new Random(seed);
}
// no methods in the class call initialize()
public int nextInt() {
return random.nextInt();
}
}Obviously, if the same method can be called after construction, the field becomes variable:
class EffectivelyFinal2 {
@Final(absent = true)
private Random random;
public EffectivelyFinal2() {
reset();
}
public void reset() {
initialize(3L);
}
private void initialize(long seed) {
random = new Random(seed);
}
public int nextInt() {
return random.nextInt();
}
}Note that it is perfectly possible to rewrite the first example in such a way that the final modifier can be used.
From the point of view of the analyzer, this does not matter.
The wider definition will allow for more situations to be recognized for what they really are.
When an object consists solely of primitives, or deeply immutable objects such as java.lang.String, having all
fields effectively final is sufficient to generate an object that is again deeply immutable.
class DeeplyImmutable1 {
public final int x;
public final int y;
public final String message;
public DeeplyImmutable1(int x, int y, String message) {
this.message = message;
this.x = x;
this.y = y;
}
}class DeeplyImmutable2 {
@Final
private int x;
@Final
private int y;
@Final
private String message;
public DeeplyImmutable2(int x, int y, String message) {
this.message = message;
this.x = x;
this.y = y;
}
public String getMessage() {
return message;
}
public int getX() {
return x;
}
public int getY() {
return y;
}
}Examples 3 and 4 are functionally equivalent: there is no way of changing the values of the fields once they have been set. In the real world there may be a reason why someone requires the getters. Or, you may be given code as in Example 1, but you are not allowed to change it. Whatever the reason, the analyzer should recognize effective finality.
Note that we will not make a distinction between any of the different non-private access modes in Java. Only the private modifier gives sufficient guarantees that no reassignment to the fields is possible.
We now have observed that for the purpose of defining immutability, having all your fields effectively final can be sufficient in certain, limited circumstances.
The analyzer annotates types which are not immutable, but whose fields are all effectively final, with @FinalFields .
Types that have at least one variable field are never immutable, and are optionally annotated with @FinalFields(absent=true) .
Note that the record type enforces explicitly final fields, along with additional support for equality and visibility.
Any record will therefore be at least @FinalFields .
We will in this work make a distinction between a property being effectively or eventually present. The former indicates a property as computed after construction of the object, which is potentially a little broader than the definition of the language. The latter is used when this property can only be obtained after the code reaches a certain state. More on this later, but here is a first example of a type with eventually final fields:
SetOnceimport java.util.Random;
@FinalFields(after="random")
class OneRandom {
private Random random;
@Mark("random")
public void set(Random r) {
if(r == null) throw new NullPointerException();
if(this.random != null) throw new IllegalStateException("Already set");
this.random = r;
}
@Only(after="random")
public Random get() {
if(this.random == null) throw new IllegalStateException("Not yet set");
return this.random;
}
}Once a value has been set, the field random cannot be assigned anymore.
We have just observed that if one restricts to primitives and types like java.lang.String, final fields are sufficient
to guarantee deep immutability.
It is not feasible, and we do not wish to, work only with deeply immutable objects.
Moreover, it is easy to see that final fields alone are not enough to guarantee what we intuitively may think immutability
stands for:
@FinalFields
class StringsInArray {
private final String[] data;
public StringsInArray(String[] strings) {
this.data = strings;
}
public String getFirst() {
return data[0];
}
}
...
String[] strings = { "a", "b" };
StringsInArray sia = new StringsInArray(strings);
Assert.assertEquals("a", sia.getFirst());
strings[0] = "c"; (1)
Assert.assertEquals("c", sia.getFirst()); (2)| 1 | External modification of the array. |
| 2 | As a consequence, the data structure has been modified. |
To continue, we must first understand the notion of modification.
3. Modification
We use the term 'object graph' to denote the fields of the object, the fields of these fields, etc., to arbitrary depth.
Consequently, a method is not modifying if it only reads from the object graph of the fields.
The analyzer uses the annotations @NotModified and @Modified .
They are exclusive, and the analyzer will compute one or the other for every method of the type.
All non-trivial constructors are modifying, so we avoid clutter by not annotating them.
Why not @Modifying and @NotModifying? The analyzer will compute modifications of fields and parameters as well.
They will either be modified or not modified by the code. To avoid
confusion, we only use one set of annotations. |
It follows from the definition that directly assigning to the fields also causes the @Modified mark for methods.
As a consequence, setters are @Modified , while getters are @NotModified.
Consider
class Counter {
// variable
private int counter;
@NotModified
public int getCounter() {
return counter;
}
@Modified
public int increment() {
counter += 1;
return counter;
}
}
@FinalFields
class CountedInfo {
@Modified
private final Counter counter = new Counter();
@Modified
public void printInfo(String info) {
System.out.println("Message " + counter.increment() + ": "+info);
}
}We also see in the example that the printInfo method is @Modified .
This is because it calls a modifying method on one of its fields, increment.
Moving from methods to parameters and fields, keeping the same two annotations,
We will apply a similar reasoning to a field:
Let us start by agreeing that the methods of Object and String are all @NotModified.
This is pretty obvious in the case of toString, hashCode, getClass.
It is less obvious for the wait and other synchronization-related methods, but remember that as discussed in
the Assumptions, we exclude synchronization support from this discussion.
Note also that we cannot add modifying methods to the type DeeplyImmutable1 defined earlier.
Proceeding, let us also look at (a part of) the Collection interface, where we have restricted the annotations
to @NotModified and @Modified — others will be introduced later.
An abstract method without @NotModified is assumed to be modifying, i.e., @Modified is implicitly present.
The reason for this choice is that from the point of view of the analyzer, modification is the default behavior.
The analyzer must prove non-modification.
public interface Collection<E> extends Iterable<E> {
boolean add(E e);
boolean addAll(@NotModified Collection<? extends E> collection);
@NotModified
boolean contains(Object object);
@NotModified
boolean containsAll(@NotModified Collection<?> c);
@NotModified
void forEach(Consumer<? super E> action);
@NotModified
boolean isEmpty();
boolean remove(Object object);
boolean removeAll(@NotModified Collection<?> c);
@NotModified
int size();
@NotModified
Stream<E> stream();
@NotModified
Object[] toArray();
}Adding an object to a collection (set, list) will cause some assignment somewhere inside the data structure. Returning the size of the collection should not.
Under supervision of the analyzer, you will not be able to create an implementation of this interface
which violates the modification rules.
This is intentional: no implementation should modify the data structure when e.g. size is called. |
Adding all elements of a collection to the object (in addAll) should not modify the input collection, whence the @NotModified.
Other types in the parameters have not been annotated with @NotModified:
Objectbecause it is immutable;Ebecause it is of an unbounded generic type, it has the same methods available asObject. No code visible to implementations ofCollectioncan make modifications toEwithout explicit down-casting;Consumerbecause it is a function type, an interface ofjava.util.function; such parameters are@IgnoreModificationsby convention, as explained in [function-types].
In order to keep the narrative going, we defer a discussion of modification in the context of parameters of abstract types to the sections Abstract methods and More on hidden content. Here, we continue with the first use case of modification: containers.
4. Containers
Loosely speaking, a container is a type to which you can safely pass on your objects, it will not modify them. This is the formal rule:
Whatever else the container does, storing the arguments in fields or not, it will not change the objects you pass to it. You obviously remain free to change them elsewhere; then the container may hold on to the changed object.
Containers are complementary to immutable objects, and we will find that many immutable objects are containers, while some containers are the precursors to immutable types. There are two archetypes for containers: collections and builders.
The simple but useful utility type Pair trivially satisfies the container requirements:
Pair of objects@Container
public class Pair<K,V> {
public final K k;
public final V v;
public Pair(K k, V v) {
this.k = k;
this.v = v;
}
@NotModified
public K getK() {
return k;
}
@NotModified
public V getV() {
return v;
}
}While its fields are clearly final, it will remain to be seen if it satisfies all criteria for intuitive immutability. However, it is easily recognized as a container: a type you use and trust to hold objects.
Containers occur frequently as static nested types to build immutable objects. Examples of these will follow later, after the definition of immutability.
In the following example, the first class is computed to be a container, the second is a container according to the contract, and the third is a class which cannot be a container:
@Container
class ErrorMessage {
// variable
private String message;
public ErrorMessage(String message) {
this.message = message;
}
@NotModified
public String getMessage() {
return message;
}
@Modified
public void setMessage(String message) {
this.message = message;
}
}
@Container
interface ErrorRegistry {
@NotModified
List<ErrorMessage> getErrors();
// @Modified implicitly
void addError(@NotModified ErrorMessage errorMessage); (1)
}
class BinaryExpression extends Expression {
public final Expression lhs;
public final Expression rhs;
// ...
public void evaluate(@Modified ErrorRegistry errorRegistry) {
// ...
if(lhs instanceof NullConstant || rhs instanceof NullConstant) {
errorRegistry.addError(new ErrorMessage(...)); (2)
}
// ...
}
}| 1 | Implementations of ErrorRegistry will not be allowed to use the setMessage setter in addError, or in any
other method not mentioned here, if the errorMessage has been assigned or added to any of the fields. |
| 2 | Here a modifying method call takes place. |
The BinaryExpression class is not a container, because it uses one of the parameters of a public method,
errorRegistry of evaluate, as a writable container.
Arrays are essentially containers holding the @FinalFields property: a chunk of memory is held in an effectively final
field, and array access reads and writes from this memory object.
Indeed, consider the following semi-realistic implementation of an Integer array based on a ByteBuffer:
@Container
interface Array<T> {
@NotModified
int length();
@NotModified
T get(int index);
// @Modified implicitly
void set(int index, T t);
}
@FinalFields @Container
static class IntArray implements Array<Integer> {
private final ByteBuffer byteBuffer;
private final int size;
public IntArray(int size) {
this.size = size;
byteBuffer = ByteBuffer.wrap(new byte[size * Integer.BYTES]);
}
@Override
public int length() {
return size;
}
@Override
public Integer get(int index) {
return byteBuffer.getInt(index * Integer.BYTES);
}
@Override
public void set(int index, Integer i) {
byteBuffer.putInt(index * Integer.BYTES, i);
}
}
@Test
public void test() {
IntArray ia = new IntArray(5);
for (int i = 0; i < 5; i++) ia.set(i, i + 1);
assertEquals(3, ia.get(2));
}It would have been better to show an ErrorMessage array, because, contrary to Integer, the former is
mutable (it has a modifying method setMessage). The technical aspect of storing and
retrieving the reference to the object, which is not normally available, prevents us from doing this here.
To conclude this section, note that the definition of @Container carefully words
… modifies its arguments.
Recall that a parameter is modified when the argument’s entire object graph is modified, at any point during the
object’s life-cycle — not merely when the method that receives it contains a modifying statement.
It is not because a method does not visibly modify its argument, that no modification can exist:
class ErrorLog {
@Modified
private final List<ErrorMessage> messages = new ArrayList<>();
@Modified
public void add(@Modified ErrorMessage message) { (1)
messages.add(message);
}
@Modified
public void changeFirst() {
if(!messages.isEmpty()) {
messages.get(0).setMessage("changed!"); (2)
}
}
}| 1 | Not a single statement of add modifies message; it only stores it. |
| 2 | Yet here, an object which arrived via message is modified. |
The add method stores its argument, which makes the field messages depend on it.
The changeFirst method modifies the object graph of that field, so an object that entered the type through
message can be modified after add has returned.
The modification therefore travels, exactly as it does in Dependence: from the method changeFirst, to
the field messages, and finally to the parameter message of add, which is marked @Modified as a result.
ErrorLog is not a container, and objects passed to it are not safe from modification.
The analyzer makes this journey by following objects as they flow from parameters into fields; that is the subject of the next section.
Because modification of parameters is computed this way, the definition above is equivalent to the more practical
rule that all parameters of all non-private methods and constructors must be @NotModified — which is precisely what the
analyzer checks.
5. Dependence
Let us now elaborate on how we will compute modifications, in a path towards immutability. Consider the following example:
class LinkExample1<X> {
private final Set<X> set;
public LinkExample1(Set<X> xs) {
this.set = xs;
}
public void add(X x) {
set.add(x);
}
}After construction, an instance of LinkExample1 contains a reference to the set that was passed on as an argument to its constructor.
We say the field set depends on the parameter xs of the constructor: a modification of one is a modification of the other.
In this example, this is an expensive way of saying that there is an assignment from one to the other.
However, dependence can become more complicated.
The maddi analyzer will add modification annotations to LinkExample1 as follows:
class LinkExample1<X> {
@Modified
private final Set<X> set;
public LinkExample1(@Modified Set<X> xs) {
this.set = xs;
}
@Modified
public void add(X x) {
set.add(x);
}
}The parameter x of LinkExample1.add is @NotModified because the first parameter of Set.add is @NotModified (because its type is an unbound type parameter).
The LinkExample1.add method modifies the field, which causes the annotation first on the method, then on the field, and finally on the parameter of the constructor.
Because of the latter, LinkExample1 cannot be marked @Container .
Dependence is about the underlying object, and not about the variable.
Consider the following alternative add method:
add method for LinkExample1@Modified
public void add(X x) {
Set<X> theSet = this.set;
X theX = x;
theSet.add(theX);
}Nothing has changed, obviously. Finally, as an example of how dependence can become more complicated than following assignments, consider a typical view on a collection:
List<X> list = createSomeLargeList();
List<X> sub = list.subList(1, 5);
sub.set(0, x); (1)| 1 | The modifying method call set will modify sub, and list as well! |
On the other side of the spectrum, there is no dependence between objects that cannot be modified, like primitives or deeply immutable objects such as java.lang.String.
Let us summarize by:
Dependent objects must share a common sub-object: the object returned by subList, for example, is "backed" by the original list, in other words, it maintains a reference to the original list.
| (in)dependence is defined at the level of objects (instances of some class or interface). Two objects of the same class can be independent of each other. For two objects to be dependent on each other, they must have some common type in their respective type definitions. |
We will discuss how dependence is computed in How to compute dependence. For now, assume that a field depends on another field, or on a parameter, if there is a possibility that both variables represent (part of) the same object (their object graphs overlap).
| The analyzer finds this out by recording where objects flow: from parameters into fields, and from fields into return values. It calls such a record a link. We will meet links again in the chapters on Ownership and Nullability, which follow the same flow with a different question, and in The link system, which describes how they are computed. In this part of the document we speak of dependence, which is what the links are computed for. |
Dependence between fields and parameters, and between fields and return values of methods, is what matters to us:
When a constructor parameter is dependent, any modification made to the object presented to this parameter as an argument may have an influence on the object graph of the fields of the constructor’s type. But do all these modifications matter to the type?
5.1. Accessible and hidden content
We will try to make our case using two examples.
First, consider Counter and Counters:
interface Counter {
// @Modified implicit
void increment();
@NotModified
int getValue();
@NotModified
String getName();
}
@FinalFields @Container
class Counters {
private final Map<String, Counter> counters;
public Counters(Collection<Counter> counterCollection) {
this.counters = counterCollection.stream().collect
(Collectors.toUnmodifiableMap(Counter::getName, c -> c));
}
@NotModified
public Counter getCounter(String name) {
return counters.get(name);
}
@NotModified
public int getValue(String name) {
return getCounter(name).getValue();
}
}The constructor Counters copies every counter in the counterCollection into a new, unmodifiable map.
Clearly, external modifications to the collection itself (i.e., adding, removing a new Counter element) made after creation of the Counters object, will have no effect on the object graph of the field counters:
List<Counter> list = new ArrayList<>();
Collections.addAll(list, new CounterImpl("sunny days"), new CounterImpl("rainy days"));
Counters counters = new Counters(list);
Counter sunnyDays = list.remove(0);
assert "sunny days".equals(sunnyDays.getName());
assert sunnyDays == counters.getCounter("sunny days");However, consider the following statements executed after creating a Counters object:
int rainyDays = counters.getValue("rainy days");
Counter c = counters.getCounter("rainy days");
c.increment();
assert c.getValue() == rainyDays + 1;
assert counters.getValue("rainy days") == rainyDays + 1;An external modification (c.increment()) to an object presented to the constructor as part of the collection has an effect on the object graph of the fields, to the extent that an identical, non-modifying method call returns a different value!
We must conclude that the field counters depends on the constructor’s parameter counterCollection, even if modifications at the collection level have no effect.
Now we put the Counters example in contrast with the Levels example, where the modifying method increment()
has been removed from Counter to obtain Level:
interface Level {
@NotModified
int getValue();
@NotModified
String getName();
}
class Levels {
private final Map<String, Level> levels;
public Levels(Collection<Level> levelCollection) {
this.levels = levelCollection.stream().collect
(Collectors.toUnmodifiableMap(Level::getName, c -> c));
}
public Level getLevel(String name) {
return levels.get(name);
}
public int getValue(String name) {
return getLevel(name).getValue();
}
}We propose to split the object graph of a field into two parts: its accessible part, and its hidden part.
The type arguments that T writes in the declaration of a field are part of the declared type through which T holds the objects in that position.
In Counters, the field Map<String, Counter> counters holds its values through Counter.
To Map, the values are of its type parameter V: hidden content of the map.
To Counters, which wrote Counter, they are objects whose increment() it can call: accessible content of Counters.
The same holds for a type argument of a type of one’s own (Box<Counter> box), and for the component type of an array field.
What one type sees of an object therefore depends on who holds it: the elements of a container are hidden content of the container, and accessible content of the type that chose their type.
The definition goes by declaration, not by use: whether T actually calls one of the accessible methods does not matter.
A type that holds a Set without ever looking inside it still holds a Set; we come back to this in Generics.
When a type C extends from a parent type P, we see an instance of C as being composed of two parts: the methods and fields of P, augmented by the methods and fields of C.
Whilst the part of the parent, P, can be accessible, the part of the child C may remain hidden.
Similarly, when T implements the interface I, but the interface is used as the formal type, then the methods and fields of I are accessible, but the ones augmented by the implementation T remain hidden.
In the example of Level, implementations or extensions may be modifiable (such as Counter), but when presented with Level only, there are no modifications to be made.
Inside Levels, where we are limited to Level, no such extensions are accessible.
Armed with this definition, we split the combined object graph of the fields of a type into the accessible content, and the hidden content:
Note that we must make this distinction, because every interface is meant to be implemented, and every type, unless explicitly marked final or sealed can be extended in Java.
These extensions could be completely outside the control of the current implementation (even though we can use the analyzer to constrain them).
In the first example of this section, LinkExample1, objects of the type X form the hidden content of LinkExample1, while the Set instance is the accessible content.
In Counters, Map, String and Counter are accessible, but whatever augments Counter by implementing it remains hidden.
Exactly the same applies to Levels: Map, String and Level are accessible, but whatever augments Level by implementing it remains hidden.
One of the central tenets of our definition of immutability will be that
Recall that by definition, any modifications to the hidden content must be external to the type.
We end this section by refining dependence with respect to the accessible and hidden content of the fields. The definition given at the start of this chapter is absolute, in the sense that it covers the whole object graph of both objects.
When a parameter and a field share an object, we can ask whether that object belongs to the accessible content, given that we state that modifications to the hidden content are outside the scope of the type anyway. This gives three cases:
In other words, a parameter or method return value is dependent when a modification on the argument or returned value has the possibility to cause a modification in the accessible part of the fields.
We will elaborate on the middle case in More on hidden content. In the following sections, we will often use the term 'independent' when we mean 'not dependent', covering both the second and the third case.
In terms of annotations, dependence will be the default state for objects of types where dependence is possible.
We will not annotate it most of the time; if we do, we use the annotation @Independent(absent=true).
The annotation @Independent on parameters and methods is used when nothing is shared.
When a type is deeply immutable, @Independent is the default state, and therefore it will be omitted.
We use @Independent(hc=true) when only hidden content is shared.
Now, all pieces of the puzzle are available to introduce immutability of types.
6. Immutability
6.1. Definition and examples
First, what do we want intuitively? A useful form of immutability, less strong than deeply immutable, but stronger than final fields for many situations. We propose the following description:
Technically, immutability is much harder to define than final fields. We identify three rules, on top of the obvious final fields requirement. The first one prevents the type from making changes to its own fields:
Our friend the Pair satisfies this first rule:
Pair, revisitedpublic class Pair<K,V> {
public final K k;
public final V v;
public Pair(K k, V v) {
this.k = k;
this.v = v;
}
}Note that since K and V are unbound generic types, it is not even possible to modify their content from inside Pair, since there are no modifying methods one can call on unbound types.
The types K and V are hidden in Pair; it does not have any accessible content.
How does it fit the intuitive rule for immutability?
The type Pair holds two objects.
The type does not change their content, nor will it exchange these two objects for others, or allow others to do so.
It is clear the users of Pair may be able to change the content of the objects they put in the Pair.
Summarizing: Pair fits the intuitive definition nicely.
Here is an example which shows the necessity of the first rule more explicitly:
Point and Line@Container
class Point {
// variable
private double x;
// variable
private double y;
public Point(double x, double y) {
this.x = x;
this.y = y;
}
@NotModified
public double getX() {
return x;
}
@Modified
public void setX(double x) {
this.x = x;
}
@NotModified
public double getY() {
return y;
}
@Modified
public void setY(double y) {
this.y = y;
}
}
@FinalFields
class Line {
@Final
@Modified
private Point point1;
@Final
@Modified
private Point point2;
public Line(@Modified Point point1, @Modified Point point2) {
this.point1 = point1;
this.point2 = point2;
}
@NotModified
public Point middle() {
return new Point((point1.getX() + point2.getX())/2.0,
(point1.getY()+point2.getY())/2.0);
}
@Modified
public void translateHorizontally(double x) {
point1.setX(point1.getX() + x); (1)
point2.setX(point2.getX() + x);
}
}| 1 | Modifying operation on point1. |
The fields point1 and point2 are effectively final.
Without the translation method, the fields would be @NotModified as well.
The translation method modifies the fields' content, preventing the type from becoming immutable.
It also costs Line its @Container property: the points that were passed to the constructor are modified
(Containers).
From the restriction of rule 1, that all its fields should remain unmodified, it follows that, excluding external changes, every method call on an immutable container object with the same arguments will render the same result. We note that this statement cannot be bypassed by using static state, i.e., state specific to the type rather than the object. The definitions make no distinction between static and instance fields.
To obtain a useful definition of immutability, one which is not too strict yet follows our intuitive requirements, we should allow modifiable fields, if they are properly shielded from the modifications they intrinsically allow. We will introduce two additional rules to constrain the modifications of this modifiable data. Together with the first rule, and building on final fields, we define:
Rule 2 is there to ensure that the modifiable fields of the object cannot be modified externally by means of direct field access to the non-private fields. Rule 3 ensures that the modifiable fields of the object cannot be modified externally by obtaining or sharing references to the fields via a parameter or return value.
Types which are immutable will be marked @Immutable .
When they are containers too, which should be the large majority, we use @ImmutableContainer as a shorthand for the combination of the two annotations.
Note that:
We state that all primitive types are immutable, as is
java.lang.Object. Whilst this is fairly obvious in the case of primitives, immutability forObjectrequires us to either ignore the methods related to synchronization, or to assume that its implementation (for it is not an abstract type) has no fields. Being extensible,Objectis immutable with hidden content: the annotated JDK writes@ImmutableContainer(hc=true).A consequence of rule 1 is that all methods in an immutable type must be
@NotModified.A field whose type is an unbound type parameter, can locally be considered to be of immutable type, and therefore need not be private. This is because the type parameter could be substituted by
java.lang.Object, which we have just declared to be immutable. More details can be found in the section on Generics.Constructor parameters whose formal type is an unbound type parameter, are of hidden type inside the type of the constructor. As a consequence, rule 3 does not apply to them. This will be expanded on in More on hidden content.
The section on Inheritance will show how the immutability property relates to implementing interfaces, and sub-classing. This is important because the definition is recursive, with
java.lang.Objectthe immutable base of the recursion. All other types must extend from it.The section on Abstract methods will detail how immutability is computed for abstract types (interfaces, abstract classes).
Rules 0 and 1 can be reached eventually if there is one or more methods that effect a transition from the mutable to the immutable state. This typically means that all methods that assign or modify fields become off-limits after calling this marker method. Rule 3 can be reached eventually as well: when the object that is exposed is itself eventually immutable, so that nothing can travel through it after its own transition; or when the field is emptied at the transition, as
Lazydoes in Lazy. Eventuality for rule 2 seems too far-fetched. We address the topic of eventual immutability fully in the section Eventual immutability.When the type has fields which allow hidden content, or the type is extendable (a class that is neither
finalnorsealed, or an interface; see Inheritance), the extra parameterhc=truewill be added to the annotation. It marks a level of its own, between@FinalFieldsand immutability without hidden content: the type guarantees the part it controls, while its hidden content can still be modified by others. A type that is immutable without hidden content, such asjava.lang.String, is what we call deeply immutable.
Let us go to examples immediately.
@FinalFields @Container
class ArrayContainer1<T> {
@NotModified
private final T[] data;
public ArrayContainer1(T[] ts) {
this.data = ts;
}
@NotModified
@Independent(hc=true)
public Stream<T> stream() {
return Arrays.stream(data);
}
}After creation, external changes to the source array ts are effectively modifications to the field data.
This construct fails rule 3, as the parameter ts is dependent.
The field is a modifiable data structure, and must be shielded from external modifications.
Note the use of @Independent(hc=true) annotation on the return value of stream(), to indicate that modifications to the hidden content are possible on objects obtained from the stream.
@FinalFields @Container
class ArrayContainer2<T> {
@NotModified
public final T[] data;
public ArrayContainer2(@Independent(hc=true) T[] ts) {
this.data = Arrays.copyOf(ts, ts.length);
}
@NotModified
@Independent(hc=true)
public Stream<T> stream() {
return Arrays.stream(data);
}
}Users of this type can modify the content of the array using direct field access! This construct fails rule 2, which applies for the same reasons as in the previous example.
@ImmutableContainer(hc=true)
class ArrayContainer3<T> {
@NotModified
private final T[] data; (1)
public ArrayContainer3(@Independent(hc=true) T[] ts) {
this.data = Arrays.copyOf(ts, ts.length); (2)
}
@NotModified
@Independent(hc=true)
public Stream<T> stream() {
return Arrays.stream(data);
}
}| 1 | The array is private, and therefore protected from external modification via the direct access route. |
| 2 | The array has been copied, and therefore is independent of the one passed in the parameter. |
The independence rule enforces the type to have its own modifiable structure, rather than someone else’s. Here is the same group of examples, now with JDK Collections:
@FinalFields @Container
class SetBasedContainer1<T> {
@NotModified
private final Set<T> data;
public SetBasedContainer1(@Independent(absent=true) Set<T> ts) {
this.data = ts; (1)
}
@NotModified
@Independent(hc=true)
public Stream<T> stream() {
return data.stream();
}
}| 1 | After creation, changes to the source set are effectively changes to the data. |
The lack of independence of the constructor parameter violates rule 3 in the first example.
@FinalFields @Container
class SetBasedContainer2<T> {
@NotModified
public final Set<T> data; (1)
public SetBasedContainer2(@Independent(hc=true) Set<T> ts) {
this.data = new HashSet<>(ts);
}
@NotModified
@Independent(hc=true)
public Stream<T> stream() {
return data.stream();
}
}| 1 | Users of this type can modify the content of the set after creation! |
Here, the data field is public, which allows for external modification.
@ImmutableContainer(hc=true)
class SetBasedContainer3<T> {
@NotModified
private final Set<T> data; (1)
public SetBasedContainer3(@Independent(hc=true) Set<T> ts) {
this.data = new HashSet<>(ts); (2)
}
@NotModified
@Independent(hc=true)
public Stream<T> stream() {
return data.stream();
}
}| 1 | The set is private, and therefore protected from external modification. |
| 2 | The set has been copied, and therefore is independent of the one passed in the parameter. |
Finally, we have an immutable type. The next one is immutable as well:
@ImmutableContainer(hc=true)
class SetBasedContainer4<T> {
@ImmutableContainer(hc=true)
public final Set<T> data; (1)
public SetBasedContainer4(@Independent(hc=true) Set<T> ts) {
this.data = Set.copyOf(ts); (2)
}
@NotModified
@Independent(hc=true)
public Stream<T> stream() {
return data.stream();
}
}| 1 | the data is public, but the Set is @Immutable itself, because its content is the result of Set.copyOf, which is an implementation that blocks any modification. |
| 2 | Independence guaranteed. |
The section on Dynamic type annotations will explain how the @Immutable annotation travels to the field data.
The independence rule, rule 3, is there to ensure that the type does not expose its modifiable data through parameters and return types:
@FinalFields @Container
class SetBasedContainer5<T> {
@NotModified
private final Set<T> data; (1)
public SetBasedContainer5(@Independent(hc=true) Set<T> ts) {
this.data = new HashSet<>(ts); (2)
}
@NotModified
public Set<T> getSet() {
return data; (3)
}
}| 1 | No exposure via the field |
| 2 | No exposure via the parameter of the constructor |
| 3 | … but exposure via the getter.
The presence of the getter is equivalent to adding the modifiers public final to the field. |
Note that by decomposing rules 0 and 1, we observe that requiring all fields to be @Final and @NotModified is equivalent to requiring that all non-private fields have the final modifier, and that methods that are not part of the construction phase, are @NotModified.
The final example shows a type which violates this rule 1, because a modifying method has been added:
@FinalFields @Container
class SetBasedContainer6<T> {
@Modified
public final Set<T> set = new HashSet<>();
@Modified
public void add(@Independent(hc=true) T t) { set.add(t); }
@NotModified
@Independent(hc=true)
public Stream<T> stream() { return set.stream(); }
}6.2. Inheritance
Deriving from an immutable class is the most normal situation: since java.lang.Object is an immutable container, every class will do so.
Clearly, the property is not inherited.
Most importantly, in terms of inheritance, is that the analyzer prohibits changing the modification status of methods from non-modifying to modifying in a derived type.
This means, for example, that the analyzer will block a modifying equals() or toString() method, in any class.
Similarly, no implementation of java.util.Collection.size() will be allowed to be modifying.
The guiding principle here is that of consistency of expectation: software developers are expecting that
equals is non-modifying.
They know that a setter will make an assignment, but they’ll expect a getter to simply return a value.
No getter should ever be modifying.
The other direction is more interesting, while equally simple to explain: deriving from a parent class cannot increase the immutability level.
The one exception is the hidden content that a type has only because it can be extended: java.lang.Object is immutable with hidden content for that reason alone, and a final class deriving from it can be immutable without.
A method overriding one marked @Modified does not have to be modifying, and may be explicitly marked @NotModified: an override may strengthen a contract.
The converse, from @NotModified to @Modified , is never allowed:
abstract class MyString implements List<String> {
private String string = "";
@Override
public int size() {
string = string + "!"; (1)
return string.length();
}
@Override
@Modified (2)
public abstract String getFirst();
@Override
@NotModified (3)
public abstract boolean add(String s);
}| 1 | Not allowed!
Any implementation of List.size() (as inherited from Collection.size()) must be non-modifying. |
| 2 | Not allowed!
You cannot explicitly (contractually) change List.getFirst() from @NotModified to @Modified in a subtype. |
| 3 | This is allowed: going from @Modified to @NotModified is possible. |
Following the same principles, we observe that types deriving from a @Container super-type need not be a container themselves.
So while we may state that Collection is a container, it is perfectly possible to implement a collection which has public methods which modify their parameters, as long as the methods inherited from Collection do not modify their parameters, and the implementation does not modify the objects that depend on the parameters of the
Collection methods.
Note that sealed types reject the 'you can always extend' assumptions of Java types. In this case, all subtypes are known, and visible. The single practical consequence is that if the parent type is abstract, its annotations need not be contracted: they can be computed because all implementations are available to the analyzer.
6.3. Generics
Type parameters are either unbound, in which case they can represent any type, or they explicitly extend a given type.
Because the unbound case is simply a way of saying that the type parameter extends java.lang.Object, we can say that all type parameters extend a certain type, say T extends E.
The analyzer simply treats the parameterized type T as if it were the type E.
In the case of an unbound parameter type, only the public methods of java.lang.Object are accessible.
By definition, the type belongs to the hidden content, as defined in Accessible and hidden content.
Hidden content is decided by the declared type, not by use.
A class can hold an object of a concrete type without ever looking inside it: it calls none of its methods, save the ones from java.lang.Object, reads none of its fields, and passes it on only where a java.lang.Object would do.
Such a type could have been a type parameter, and would then belong to the hidden content.
The analyzer does not make that replacement: it judges the type as written, and a Set that the constructor stores and a getter returns is a Set.
The replacement is a refactoring, and it is the programmer’s:
@FinalFields @Container (1)
public class OddPair {
private final Set<String> set;
private final StringBuilder sb;
public OddPair(Set<String> set, StringBuilder sb) {
this.set = set;
this.sb = sb;
}
public Set<String> getSet() { return set; }
public StringBuilder getSb() { return sb; }
}| 1 | The constructor stores what it is given and the getters return it: dependent, so @FinalFields (rule 3). |
Nowhere in OddPair do we make actual use of the fact that set is of type Set, or sb is of type StringBuilder.
Replace Set by some unbound parameter type, say K, and StringBuilder by some other, say V, and the verdict becomes @ImmutableContainer(hc=true) .
The result is, of course, the type Pair as defined earlier.
Making a concrete choice for a type parameter may have an effect on the immutability status, as will be explained in
More on hidden content.
One example is easy to see: any immutable type whose hidden content consists only of types of unbound type parameter, will become deeply immutable (i.e., devoid of hidden content) when the unbound type parameters are substituted for deeply immutable types.
The Pair mentioned before is a case in point: Pair<Integer, Long> is deeply immutable.
6.4. Abstract methods
Because java.lang.Object is an immutable container, trivial extensions are, too:
java.lang.Object@ImmutableContainer (1)
interface Marker { }
@ImmutableContainer
class EmptyClass { }
@ImmutableContainer
class ImplementsMarker implements Marker { }
@ImmutableContainer
class ExtendsEmptyClass extends EmptyClass { }| 1 | Interfaces, and classes that are neither final nor sealed, are extensible, so the analyzer writes hc=true on every type in this example.
We leave it out of the interface examples of this document, for brevity. |
Things only become interesting when methods enter the picture. Annotation-wise, we stipulate that
Unless otherwise explicitly annotated, we will assume that abstract methods, be they in interfaces or abstract classes, are @Modified . |
Furthermore, we will also impose special variants of the rules for immutability of an abstract type T, to be obeyed by the abstract methods:
The consequence of these choices is that implementations and extensions of abstract and non-abstract types will have the opportunity to have the same immutability properties.
This allows us, e.g., to treat any implementation of Comparable, defined as:
java.lang.Comparable annotated@ImmutableContainer
interface Comparable<T> {
@NotModified
int compareTo(T other); // @NotModified on other, as its type is a type parameter
}as an immutable type when the only method we can access is compareTo.
As far as the modification status of the parameters of abstract methods is concerned, we also start off with @Modified :
Unless otherwise explicitly annotated, or their types are immutable, we will assume that the parameters of abstract methods, be they in interfaces or abstract classes, are @Modified .
An unbound type parameter counts as a type that is immutable here: the abstract type cannot call a modifying method on such a parameter, so it is @NotModified unless the contract says otherwise.
Overriding the method, the contract can change from @Modified to @NotModified, but not from @NotModified to @Modified . |
While it is possible to compute the immutability and container status of interface types, using the rules presented above, it often makes more practical sense to use the annotations as contracts: they may save a lot of annotation work on the abstract methods in the interface. We repeat that no implementation of an immutable interface is guaranteed to be immutable itself; nor does this guarantee hold for the container property unless no new non-private methods have been added.
We continue this section with some examples which will form the backbone of the examples in More on hidden content.
If semantically used correctly, types implementing the HasSize interface expose a single numeric aspect of their content:
HasSize interface@ImmutableContainer // computed
interface HasSize {
@NotModified // contracted
int size();
@NotModified // computed, not an abstract method!
default boolean isEmpty() {
return size() == 0;
}
}We extend to:
NonEmptyImmutableList@ImmutableContainer // computed
interface NonEmptyImmutableList<T> extends HasSize {
@NotModified // contracted
@Independent(hc=true) (1)
T first();
@NotModified // contracted
void visit(@Independent(hc=true) Consumer<T> consumer); (2) (3)
@NotModified (4)
@Override
default boolean isEmpty() {
return false;
}
}| 1 | Whilst formally, T can never be dependent because it must belong to the hidden content of the interface, contracting the @Independent(hc=true) annotation here will force all concrete implementations to have a non-dependent
first method.
Even if the concrete choice for T is modifiable, the independence rule must be satisfied. |
| 2 | The parameter consumer would normally be @Modified , which would break the @Container property that we wish for
NonEmptyImmutableList.
However, as detailed and explained in [function-types], a parameter of function type has an
implicit @IgnoreModifications annotation. |
| 3 | The hidden content of the type is exposed to the outside world via the accept method in the consumer, similarly to being exposed via the return value of the first method. |
| 4 | Computed, because it is not an abstract method.
It must (and does) agree with the @NotModified status of HasSize.isEmpty(). |
The Consumer interface is defined and annotated as:
@FunctionalInterface
interface Consumer<T> {
// @Modified implicit
void accept(@Modified T t);
}Implementations of the accept method are allowed to be modifying (even though in NonEmptyImmutableList.visit
we decide to ignore this modification!).
They are also allowed to modify their parameter, as we will demonstrate shortly: the @Modified on t is a contract, written out because a parameter whose type is a type parameter is @NotModified by default.
A Consumer exists to act on its argument, and an implementation that fixes T knows what it is given.
Let’s downgrade from @ImmutableContainer to @FinalFields @Container by adding a modifying method:
NonEmptyList@FinalFields @Container
interface NonEmptyList<T> extends NonEmptyImmutableList<T> {
// @Modified implicit
void setFirst(@Independent(hc=true) T t);
}Note that the method setFirst promises to keep its parameter unmodified thanks to the @Container annotation on the type.
The @Independent(hc=true) annotation states that arguments to setFirst will end up in the hidden content of the NonEmptyList.
Implementations can even lose @FinalFields :
NonEmptyList@Container
static class One<T> implements NonEmptyList<T> {
// variable
private T t;
@NotModified
@Override
public T first() {
return t;
}
@Modified
@Override
public void setFirst(T t) {
this.t = t;
}
@NotModified
@Override
public int size() {
return 1;
}
@NotModified
@Override
public void visit(Consumer<T> consumer) {
consumer.accept(t);
}
}Here is a (slightly more convoluted) implementation that remains @FinalFields and @Container :
NonEmptyList@FinalFields @Container
static class OneWithOne<T> implements NonEmptyList<T> {
private final One<T> one = new One<>();
@NotModified
@Override
public T first() {
return one.first();
}
@Modified
@Override
public void setFirst(T t) {
one.setFirst(t);
}
@NotModified
@Override
public int size() {
return 1;
}
@NotModified
@Override
public void visit(Consumer<T> consumer) {
consumer.accept(first());
}
}Obviously, an @ImmutableContainer implementation is not possible.
The immutability status of a class cannot be better than that of its supertypes, apart from the hidden content that extensibility brings, and no implementation of setFirst that does what its name promises can avoid a modification.
We end the section by showing how concrete implementations of the accept method in Consumer can make modifications.
First, modifications to the parameter:
Consumer.acceptOne<StringBuilder> one = new One<>();
one.setFirst(new StringBuilder());
one.visit(sb -> sb.append("!"));The last statement is maybe more easily seen as:
Consumer.accept, written outone.visit(new Consumer<StringBuilder>() {
@Override
public void accept(StringBuilder sb) {
sb.append("!");
}
});Second, modifications to the fields of the type:
Consumer.accept modifying a field@FinalFields @Container
class ReceiveStrings implements Consumer<String> {
@Modified
public final List<String> list = new ArrayList<>();
@Modified
@Override
public void accept(String string) {
list.add(string);
}
}6.5. Static side effects
Up to now, we have made no distinction between static fields and instance fields: modifications are modifications.
Inside a primary type, we will stick to this rule.
In the following example, each call to getK increments a counter, which is a modifying operation because the type owns the counter:
A primary type T is a type defined in its own file, i.e., T.java.
It is not nested inside some other type. |
@FinalFields @Container
public class CountAccess<K> {
@NotModified
private final K k;
@Modified
private static final AtomicInteger counter = new AtomicInteger();
public CountAccess(K k) {
this.k = k;
}
@Modified
public K getK() {
counter.getAndIncrement();
return k;
}
@NotModified
public static int countAccessToK() {
return counter.get();
}
}We can explicitly ignore modifications with the contracted @IgnoreModifications annotation, which may make sense from a semantic point of view:
@ImmutableContainer(hc=true)
public class CountAccess<K> {
@NotModified
private final K k;
@IgnoreModifications
private static final AtomicInteger counter = new AtomicInteger();
public CountAccess(K k) {
this.k = k;
}
@NotModified (1)
public K getK() {
counter.getAndIncrement(); (1)
return k;
}
@NotModified
public static int countAccessToK() {
return counter.get();
}
}| 1 | The effects of the modifying method getAndIncrement are ignored. |
Note that when the modification takes place inside the constructor, it is still not ignored, because for static fields, static code blocks act as the constructor:
@FinalFields @Container
public class HasUniqueIdentifier<K> {
public final K k;
public final int identifier;
@Modified
private static final AtomicInteger generator = new AtomicInteger();
public HasUniqueIdentifier(K k) {
this.k = k;
identifier = generator.getAndIncrement();
}
}Only modifications in a static code block are ignored:
public class CountAccess<K> {
...
private static final AtomicInteger counter;
static {
counter = new AtomicInteger();
counter.getAndIncrement(); (1)
}
...
}| 1 | Modification, part of the construction process. |
Nevertheless, we introduce the following rule which does distinguish between modifications on static and instance types:
The callee may be static or not, or a constructor: what counts is whose static state changes, not how it is reached. A type modifying its own static state has no static side effect, but its callers in other types do:
class Counter {
private static int count;
static int next() { return ++count; } (1)
}
class Client {
@StaticSideEffects (2)
static int twice() { return Counter.next() + Counter.next(); }
}| 1 | Counter’s own static state: not a static side effect. |
| 2 | Not Client’s: a static side effect. Constructing a HasUniqueIdentifier from another type is one too. |
This is still consistent with the rules of immutable types, which only look at the fields and assume that when methods do not modify the fields, they are actually non-modifying.
Without an @IgnoreModifications annotation on the field System.out (which we would typically add), printing to the console results in
@StaticSideEffects
@NotModified
public K getK() {
System.out.println("Getting "+k);
return k;
}We leave it up to the programmer or designer to determine whether static calls deserve a @StaticSideEffects warning, or not.
In almost all instances, we prefer a singleton instance (see Singleton classes) over a class with modifying static methods.
In singletons the normal modification rules apply, unless @IgnoreModifications decorates the static field giving access to the singleton.
6.6. Ignoring modifications as manual hidden content
We have now used @IgnoreModifications on a field twice: on the access counter of CountAccess, and on System.out.
In both cases we argued informally that the modification "does not matter" to the type.
This section makes that argument precise, by relating the annotation to hidden content
(Accessible and hidden content, and later More on hidden content).
Take a type that keeps a record of how it is used:
@ImmutableContainer(hc=true)
class Catalogue {
private final Map<String, Price> prices; // Price is immutable
@IgnoreModifications
private final List<String> lookups = new ArrayList<>(); (1)
public Catalogue(Map<String, Price> prices) {
this.prices = Map.copyOf(prices);
}
@NotModified
public Price price(String item) {
lookups.add(item); (2)
return prices.get(item);
}
}| 1 | A concrete, modifiable type; the annotation is a contract. |
| 2 | A modifying method call on a field, ignored. |
Now recall why the hidden content of a type never threatens its immutability.
Pair<K, V> holds two objects of which it knows nothing but their type parameter.
A client can modify them; Pair cannot, because it has no method to call on them, and it cannot be held
responsible: Pair stays @Immutable(hc=true) .
The modifications are not part of its immutability contract.
The @IgnoreModifications annotation on lookups says exactly the same thing about a field of a concrete type:
modifications to this field’s object are not part of my immutability contract.
The two are interchangeable in the definition of immutability.
They differ in where the "not my concern" judgement comes from.
For a type parameter it is derived, and always correct: the type cannot do anything with a K.
For an ignored field it is asserted, and List<String> has plenty of methods to do things with.
An assertion needs a check.
6.6.1. The confinement guard
An ignored field is sound hidden content when a modification made through it stays inside the ignored part: the objects that can only be reached through that field. It must not escape into the accessible content of the type, nor into global state. We call this property confinement. It has two sides.
The first is separation: the ignored field must be @Independent of the type’s accessible content.
In Catalogue, add a field and a method:
private final Offer base; // accessible content; Offer has a modifying method 'discount'
@IgnoreModifications
private final List<Offer> recent = new ArrayList<>();
public void touch() {
recent.add(base); (1)
recent.get(0).discount(); (2)
}| 1 | Allowed: the ignored part may refer to accessible content. |
| 2 | An escape: the modification, made through the ignored field, lands on base. |
The second is containment: every modifying call on the ignored field must keep its effect to the receiver, and touch no accessible field, no parameter, and no global state. With a stream as the example:
| call | effect | verdict |
|---|---|---|
| writes the object’s own buffer / entries | confined — allowed |
| replaces a global reference | escapes — flagged |
Printing to a stream is using it; replacing the stream that everybody prints to is an escape.
6.6.2. What is not an escape
Two operations look like modifications, but stay inside the ignored part:
writing into it: appending to a log, putting into a metadata store;
referring to accessible content from it: storing a reference to an accessible object inside the ignored object, as in the first callout above.
The example closest to home is the analyzer itself. It reads an immutable syntax tree, and records what it finds in a property map held on each node:
@ImmutableContainer(hc=true)
class FieldNode {
private final String name;
private final TypeNode type;
@IgnoreModifications
private final Map<String, Object> analysis = new HashMap<>();
...
@NotModified
public void record(String property, Object value) {
analysis.put(property, value); (1)
}
}
...
fieldNode.record("assignedIn", methodNode); (2)| 1 | Writing into the ignored part. |
| 2 | The value refers back into the tree. |
The analyzer writes these maps constantly; that is its whole purpose. Neither callout is an escape:
The guard would fire if the analyzer took a node out of the map and modified one of its proper fields, such as name
or type: a genuine violation of the tree’s immutability, and exactly what the guard exists to show.
Confinement can only be checked on code that is visible. When the code modifying the ignored part is out of sight, the annotation is an assumption; once all of it is in sight, it is a verified property.
6.6.3. Static side effects are the global escape
The static side effects of Static side effects fit in this picture: they are one branch of the confinement guard, met earlier. The two annotations divide the work by who holds the state:
@IgnoreModificationsgoverns content the type holds through one of its own fields;@StaticSideEffectsgoverns state the type does not hold at all: a modification of another type’s static state, which cannot be declared your hidden content because it is not your field.
Where an escape lands determines its consequence:
| the escape lands on… | consequence |
|---|---|
the type’s own accessible content | a warning: it is unsound to ignore the modification. The decision is left to the designer, and the immutability verdict stands as contracted |
global / static state you do not own | no effect on immutability, which looks at your fields only; but a real outward effect, marked |
So @StaticSideEffects covers precisely what the reading as manual hidden content cannot: an effect that does not touch your
immutability, yet is a genuine outward effect that the designer should see.
And the two compose: @IgnoreModifications on the target field turns a @StaticSideEffects from an unaccounted outward effect
into a disclaimed one.
This is the System.out story of the previous section, read from the side of the field’s owner: without the
@IgnoreModifications on System.out, println is a @StaticSideEffects ; with it, printing is a modification of sanctioned hidden
content.
6.6.4. Escapes that cannot be seen
In source code, a static side effect is visible: an assignment to, or a modifying call on, another type’s static
field, directly or through the methods called.
But the sharpest escapes are not in source code.
System.setOut(other) replaces the process-wide System.out, and nothing in what can be seen of the JDK says so.
An invisible escape is recorded in the only way it can be: as a contract in the annotated API of the library.
class System$ { // annotated-API stand-in for java.lang.System
@IgnoreModifications static final PrintStream out = null;
@StaticSideEffects static void setOut(PrintStream out) { } // effect invisible from source
}A caller of a @StaticSideEffects method inherits the static side effect, transitively.
This is how the confinement guard tells reconfiguring a stream from using it: sink.reconfigure() on an
@IgnoreModifications field, where reconfigure() calls System.setOut, receives @StaticSideEffects , and the guard flags the call
as leaving the ignored part; sink.println(x), calling only the confined println, passes.
@StaticSideEffects is a contract where there is no body to compute it from: a library method, or an abstract one.
On a method with source, the analyzer computes it; an author who writes it there asserts it, and the assertion is
taken as a contract.
6.7. Value-based classes
Quoting from the JDK documentation (the definition has been sharpened since JDK 8), value-based classes are
final and immutable (though may contain references to mutable objects);
have implementations of equals, hashCode, and toString which are computed solely from the instance’s state and not from its identity or the state of any other object or variable;
make no use of identity-sensitive operations such as reference equality (==) between instances, identity hash code of instances, or synchronization on an instance’s intrinsic lock;
are considered equal solely based on equals(), not based on reference equality (==);
do not have accessible constructors, but are instead instantiated through factory methods which make no commitment as to the identity of returned instances;
are freely substitutable when equal, meaning that interchanging any two instances x and y that are equal according to
equals()in any computation or method invocation should produce no visible change in behavior.
Item 1 requires final fields but does not specify any of the restrictions we require for immutability.
Item 2 implies that should equals, hashCode or toString make a modification to the object, its state changes, which would then change the object with respect to other objects.
We could conclude that these three methods cannot be modifying.
Loosely speaking, objects of a value-based class can be identified by the values of their fields.
Immutability is not a requirement to be a value-based class.
However, we expect many immutable types will become value-classes.
Revisiting HasUniqueIdentifier from Static side effects, we can construct a counter-example:
@ImmutableContainer(hc=true)
public class HasUniqueIdentifier<K> {
public final K k;
public final int identifier;
@IgnoreModifications // as on the counter of CountAccess
private static final AtomicInteger generator = new AtomicInteger();
public HasUniqueIdentifier(K k) {
this.k = k;
identifier = generator.getAndIncrement();
}
@Override
public boolean equals(Object other) {
if(this == other) return true;
if(other instanceof HasUniqueIdentifier<?> hasUniqueIdentifier) {
return identifier == hasUniqueIdentifier.identifier;
}
return false;
}
}The equals method violates item 2 of the value-class definition, maybe not to the letter but at least in its spirit:
the field k is arguably the most important field, and its value is not taken into account when computing equality.
6.8. Dynamic type annotations
When it is clear a method returns an immutable set, but the formal type is java.util.Set, the @Immutable annotation can 'travel':
SetBasedContainer4@ImmutableContainer(hc=true)
class SetBasedContainer4<T> {
@ImmutableContainer(hc=true)
public final Set<T> data;
public SetBasedContainer4(Set<T> ts) {
this.data = Set.copyOf(ts);
}
@ImmutableContainer(hc=true)
public Set<T> getSet() {
return data;
}
}Whilst Set in general is not @Immutable , the data field itself is.
The analyzer computes them with the machinery that also propagates eventual immutability (Eventual immutability): the verdict travels with the value.
6.9. Unmodifiable views
Collections.unmodifiableList(list) returns a view: an object that never adds anything to or removes
anything from the list it wraps, and that throws when asked to.
It is not immutable.
Whoever still holds list can change it, and the view shows the change.
The chapter on Dependence introduced views as the place where dependence stops being a matter of
following assignments; here we ask what the definitions of this chapter make of them.
Run the view’s type through the rules.
Its one field is final (rule 0), nothing in the type modifies it (rule 1), it is private (rule 2) — and the
constructor stores the list it is given, so the field is dependent on a parameter, and rule 3 fails.
The verdict is @FinalFields .
That verdict is correct and not very informative: @FinalFields does not say whether rule 1 failed or only
rule 3 did, and the difference is exactly what matters to anyone holding the view.
A Bag with an add method is @FinalFields too.
So we give the weaker fact a name of its own, beside immutability and never derived from it:
An @Immutable(hc=true) type is unmodifiable by implication; the converse does not hold, and that is the point:
@UnmodifiableView is what a view may claim and @Immutable(hc=true) is what it may not.
The annotation says nothing about @Container either.
The name follows JetBrains' annotation of the same meaning.
On a method without a body, @UnmodifiableView is a contract.
In the JDK, the Collections.unmodifiable* factories carry it.
On a method with a body, the analyzer computes it from the values the method returns: a call to a method
with the property, an instance of an unmodifiable type, a value that is at least @Immutable(hc=true) , a field
proven to hold one, or null.
On a bodiless declaration with implementations, it is the fold over the implementations, as for the other
method properties of Abstract methods.
@FinalFields
static class View { (1)
private final List<String> list;
View(List<String> list) { this.list = list; }
String get(int i) { return list.get(i); }
int size() { return list.size(); }
}
@FinalFields
static class Bag { (2)
private final List<String> list = new ArrayList<>();
@Modified void add(String s) { list.add(s); }
int size() { return list.size(); }
}
@FinalFields
static class Wraps {
private final List<String> list = new ArrayList<>();
@UnmodifiableView
List<String> view() { return Collections.unmodifiableList(list); } (3)
List<String> copy() { return new ArrayList<>(list); } (4)
@UnmodifiableView
List<String> both(boolean b) { return b ? Collections.unmodifiableList(list) : null; }
@UnmodifiableView
View asView() { return new View(list); } (5)
@UnmodifiableView
List<String> chained() { return view(); }
@ImmutableContainer(hc=true)
List<String> frozen() { return List.copyOf(list); } (6)
}| 1 | Rules 0, 1 and 2 hold, rule 3 fails: @FinalFields , and an unmodifiable type. |
| 2 | Rule 1 fails: @FinalFields , and not unmodifiable. |
| 3 | The contract on Collections.unmodifiableList travels to the caller. |
| 4 | A fresh, modifiable copy: nothing to claim. |
| 5 | An instance of an unmodifiable type. |
| 6 | The stronger fact, when it holds: a copy that is immutable with hidden content, as in Dynamic type annotations. |
Neither property feeds the immutability, independence or container analyses; the lattice of this chapter is
unchanged.
Their consumer is the translation into Kotlin, whose collection types distinguish List<String> from
MutableList<String>: a field that is only ever given an unmodifiable view, and a method that returns one,
print with the read-only type, while the call itself stays Collections.unmodifiableList(..), because
Kotlin’s listOf would copy.
7. Ownership
The previous chapters asked who can modify an object. Independence (Dependence) answers whether modifications can travel between two objects; it lets two holders share immutable content, because nothing can travel through it. This chapter asks a different question: who holds an object?
Why would we want to know? Inside Java, an object with a single holder is the one object that is always safe to modify: nobody else is there to be surprised. We will see in Ownership and eventual immutability that this gives a second road to immutability, next to the copy and the mark. Outside Java, the question is unavoidable as soon as code has to be translated into a language without a garbage collector. In Rust, an object has one owner, and its lifetime is that of its owner; a value held in several places must be wrapped in a shared, reference-counted handle. A field whose object nobody else holds can be a plain field; a method whose result nobody else holds can return it by value; a parameter the method does not keep can be borrowed.
Ownership differs from independence in two ways.
Immutable sharing counts. A field holding a
Stringthat its caller passed in is independent of that caller, as modifications cannot travel through aString; but the object is shared, so the field does not own it.Ownership is a claim about the absence of other holders. Where independence can be assumed until a link shows up, ownership must be proven: whenever we do not know what a method does with an object, we must assume it is shared.
Three annotations express the verdicts: @Fresh on a method, @Borrowed on a parameter, @Owned on a field.
7.1. Fresh methods
In practice, every return path must yield an object created in the method, the result of a call to another
fresh method, or null; and no link may lead from that object to the receiver, a parameter, a field or a static.
class Lines {
static final List<Object> registry = new ArrayList<>();
private final List<String> lines = new ArrayList<>();
@Fresh
List<String> copy() { (1)
return new ArrayList<>(lines);
}
@Fresh
List<String> sorted() { (2)
List<String> result = copy();
Collections.sort(result);
return result;
}
List<String> orEmpty(List<String> list) { (3)
return list == null ? new ArrayList<>() : list;
}
List<String> registered() { (4)
List<String> result = new ArrayList<>();
registry.add(result);
return result;
}
}| 1 | A new object, holding the elements of lines: the elements are shared, the list is not. |
| 2 | The result of a fresh method, modified before it is returned: still fresh. |
| 3 | One return path yields the parameter. |
| 4 | The new object is also held by registry. |
Note the first callout: freshness is about the object itself, not about its hidden content. The copy is a new list; the strings in it are as shared as they were before.
A lambda or a method reference is not a created object: the Java Language Specification allows every evaluation of the same lambda to return the same instance (JLS 15.27.4, 15.13.3), so a method returning one is not fresh.
On a method without a body, an abstract method or a library method in the annotated APIs, @Fresh is a contract
that every implementation must honour.
In the JDK, Arrays.copyOf, Collection.toArray(), ArrayList.clone, String.toCharArray and Map.entry are fresh,
for example.
List.copyOf is not: it may return its argument.
Neither is Collections.emptyList, which returns a shared instance.
An abstract method without a contract is fresh only when all its implementations are.
7.2. Borrowed parameters
A borrowing method may read the object, modify it, and keep what it contains.
class Lines {
private final List<String> lines = new ArrayList<>();
int countEmpty(@Borrowed List<String> list) { (1)
int n = 0;
for (String s : list) if (s.isEmpty()) n++;
return n;
}
void addAll(@Borrowed Collection<String> c) { (2)
lines.addAll(c);
}
void add(String line) { (3)
lines.add(line);
}
Runnable printer(List<String> list) { (4)
return () -> list.forEach(System.out::println);
}
}| 1 | Read only. |
| 2 | addAll copies the elements: lines holds the strings, not the collection. |
| 3 | lines holds the object itself. It is a String, so line is independent, but not borrowed. |
| 4 | The returned lambda captures the parameter. |
The method keeps a parameter when a field of the receiver, a static, the return value, another parameter’s content,
or a lambda or object that escapes, holds a link to the parameter’s object itself.
A link to its hidden content does not count: that is the case of addAll.
Keeping is transitive: calling a method that keeps its argument keeps it too.
The second and third callouts show the two questions side by side.
For independence there is no difference between them: both c and line are @Independent , as nothing can travel
through a String.
With a type parameter T in the place of String, both would be @Independent(hc=true) (Content dependence): what they bring
ends up in the hidden content of lines.
For ownership, the difference is which object ends up in the list: the elements of c, or line itself.
On a parameter of a method without a body, @Borrowed is a contract, which every implementation must honour.
7.3. Owned fields
Three conditions make a field owned; they mirror the way an object can come to have a second holder.
It arrives fresh. Every value assigned to the field, in constructors, initializers and methods, is an object created for it, the result of a fresh method, or
null. A parameter qualifies only when it is transferred (Transfer). An unmodifiable view (Collections.unmodifiableList(x)and the rest of that family, see Unmodifiable views) arrives fresh when the object it wraps does: the view holds that object and nothing else.It never leaves. No link takes the field’s object to a return value, a parameter, a static, a field of another object, or an escaping lambda. Passing it to a borrowed parameter is allowed, and so is returning it from a method whose result every caller only uses and does not keep. We call the latter lending; it is Rust’s
&self.f.It cannot be taken. The field is private: no code outside the type can read the reference directly.
Compare these with the rules of immutability in Immutability: the third is rule 2, and the first two are rule 3, with 'not dependent' sharpened to 'not held'.
public class Document {
@Owned
private final List<String> lines = new ArrayList<>(); (1)
@Owned
private StringBuilder buffer; (2)
private final List<String> tags; (3)
private final Map<String, String> index = new HashMap<>(); (4)
public Document(List<String> tags) {
this.tags = tags;
}
public void append(String s) {
if (buffer == null) buffer = new StringBuilder();
buffer.append(s);
lines.add(s);
}
public Map<String, String> index() {
return Collections.unmodifiableMap(index);
}
}| 1 | Created for the field, and it never leaves. |
| 2 | Created lazily: every assignment is still a creation. Note that ownership does not require the field to be final: the owner may replace what it owns. |
| 3 | The public constructor stores its parameter, which a caller may go on using. |
| 4 | The unmodifiable view shares the object: a holder of the view sees every change to index. |
A field that is not owned only because it shares an immutable object (a String, say, stored from a parameter) is
shared immutable: in Rust, a reference-counted value nobody modifies.
There is no annotation for it, as @Immutable on the field’s type says it.
Static fields and fields of primitive type are not considered.
@Owned has one parameter, elements.
@Owned(elements = true) says that the elements of the field’s collection, map or other generic object, its hidden
content, are owned too: each arrives created for it, or is handed over by every caller (Transfer), and
none leaves.
In Rust, such a field is a vector of plain values rather than of shared handles.
Unlike @Fresh and @Borrowed , @Owned is never a contract: it concerns a field, which only the code of its own type
can judge.
7.4. Transfer
The first condition rejects a field assigned from a parameter: in general the caller may go on using the object. But when we can see every call site, we can check that they do not.
public class Parser {
@Owned
private final List<Token> tokens; (1)
private Parser(List<Token> tokens) {
this.tokens = tokens;
}
public static Parser of(String source) {
List<Token> tokens = new ArrayList<>();
tokens.add(new Token(source)); (2)
return new Parser(tokens); (3)
}
}| 1 | Owned: the private constructor’s only caller hands its list over. |
| 2 | Before the hand-over, the local is only the receiver of calls that keep nothing of it. |
| 3 | The last use of tokens. |
When are all call sites known? Certainly when the method is private. For any other method, it depends on what the code is: in a library, the callers are yet to be written; in an application analysed as a whole, a closed world, no code outside it calls its methods. A package-private method is no exception: a package is not closed, as anyone can add a class to it, the tests of the library to begin with. This is the assumption of Assumptions again: a method is private, or it is not. We will meet the same distinction in Who calls?. The method must also not override anything, nothing may override it, and no method reference may name it: each of these is a call site we cannot see.
@Finalizer , the subject of the next section, is a transfer of the receiver.
7.5. Finalizers
Up to now, we have focused on the distinction between the building phase of an object’s life-cycle, and its
subsequent immutable phase.
We have ignored the destruction of objects: critically important for some applications, but often completely
ignored by Java programmers because of the silent background presence of the garbage collector.
The annotation @Finalizer marks that calling a certain method means that the object has reached the end of its
life-cycle:
Why is this useful?
The most obvious use-case for immutability is the meaning of the build() method in a builder: can you call it once,
or is the builder somehow incremental?
Secondly, consider "terminal" operations such as findAny or collect on a stream. They close the stream,
after which you are not allowed to use it anymore.
In the terms of this chapter, a finalizer is a transfer of the receiver: the caller hands the object over to the call, and does not use it afterwards.
7.5.1. A finalizer does not modify
Whatever the finalizer does to the dying object is invisible to the rest of the program: there is no "after" in which the change could be observed. We can therefore state:
This is not a corner case; it is what makes stream-based code fit the definitions of this document.
The stream operations filter, map, flatMap, collect, and their relatives each consume the stream they are
called on: using the receiver again afterwards is illegal.
They are finalizers, and none of them can promise to be @NotModified.
@ImmutableContainer(hc=true)
class Names {
private final List<String> names;
public Names(List<String> names) {
this.names = List.copyOf(names);
}
@NotModified
public List<String> upperCase() {
return names.stream() (1)
.map(String::toUpperCase) (2)
.toList();
}
}| 1 | A new stream, dependent on the field names. |
| 2 | A modifying call on that stream, in the plain reading. |
Without the statement above, the modification at the second callout would travel from the stream to the field names,
and from there to the method: every method containing a stream pipeline would be @Modified , and no type with such
a method could be immutable.
With it, the pipeline is silent about its receivers, and only genuine evidence, such as what the lambda captures and
modifies, or where the collector puts its results, determines the verdict.
7.5.2. Sequencing rules
How can the analyzer enforce the sequence of method calling on an object? The simplest way is by some severe restrictions:
There is no rule that a field holding such an object must be final. As for any owned field (Owned fields), the owner may replace what it holds; the object it drops is never finalized, so nothing can be called on it afterwards.
These restrictions help you control the life-cycle of objects with a @Finalizer , by not letting them out of sight.
Each of them is an ownership rule:
| Rule | In ownership terms |
|---|---|
no method may be called after the finalizer | the receiver is not used after the call: a transfer (Transfer), with the receiver as the argument |
1. a finalizer is called on a field only inside a finalizer | an owner consumes what it owns only while it is itself consumed (in Rust, moving out of a field needs |
2. not on a parameter, or anything dependent on it, unless it is transferred | a borrowed object cannot be consumed; one that was handed over can (in Rust, a parameter taken by value) |
The eventually immutable types of the next chapter use finalizers to keep an object in its before state while it is held by a field (Finalizers in the before state).
7.5.3. Handing over what you own
The second condition for an owned field says it never leaves. A finalizer is the one place where it may: after the call, its owner is dead, so the object still has a single holder.
class Report {
private final List<String> lines;
private Report(List<String> lines) {
this.lines = lines;
}
static class Builder {
@Owned
private final List<String> lines = new ArrayList<>();
@Fluent
Builder add(String line) {
lines.add(line);
return this;
}
@Finalizer
Report build() {
return new Report(lines); (1)
}
}
}
...
Report report = new Report.Builder().add("a").add("b").build(); (2)| 1 | The owned list leaves the builder; this is allowed in a finalizer only. |
| 2 | The builder is a temporary: nothing can use it after build(). |
The two callouts are the two sides of the annotation.
A method needs to be a finalizer when it hands over an owned field of its own type; it is permitted to be one
when every call site hands over the receiver: a temporary (a construction, a fresh method’s result, a chain of
@Fluent calls on one), or a local that is not used after the call.
The analyzer computes @Finalizer only when both hold.
Call-site evidence alone would be vacuous: any method called once, on a temporary, would qualify.
A builder is there to be called from elsewhere, so its call sites are known only in a closed world
(Transfer); in a library, @Finalizer on build() is a contract.
For a contracted finalizer, the same test on every call site finds the uses of the receiver after the call, for
example a stream used again after map.
They are reported as warnings: the statement of A finalizer does not modify relies on them not happening.
7.6. Ownership and independence
Ownership is a stronger form of independence for one field, parameter or result: an owned field is independent, since no other holder exists through which a modification could travel; and a borrowed parameter is independent, since nothing retains it. The converse does not hold, because independence allows immutable sharing. The fields of this chapter’s examples, side by side:
| Field | Independent | Owned | Why |
|---|---|---|---|
| a single holder: nothing can travel, nobody else can reach it | ||
| shared, but nothing can travel through a | ||
|
| ||
| the caller holds the list, and can modify it |
There is no row with an owned, dependent field.
8. Eventual immutability
In this section we explore types which follow a two-phase life cycle: they start off as mutable, then somehow become immutable.
8.1. Builders
We start with the well-established builder pattern.
@ImmutableContainer(hc=true)
class Point {
public final double x;
public final double y;
public Point(double x, double y) {
this.x = x;
this.y = y;
}
}
@ImmutableContainer(hc=true)
class Polygon {
@ImmutableContainer(hc=true)
public final List<Point> points;
private Polygon(List<Point> points) { (1)
this.points = points;
}
@FinalFields @Container(builds=Polygon.class)
static class Builder {
@Modified
private final List<Point> points = new ArrayList<>();
@Modified
public void addPoint(Point point) {
points.add(point);
}
@NotModified
public Polygon build() {
return new Polygon(List.copyOf(points));
}
}
}| 1 | The private constructor combined with the construction of an immutable copy in the build method guarantees
immutability. |
If your code can live with two different types (Polygon.Builder, Polygon) to represent polygons in their different
stages (mutable, immutable), the builder paradigm is great.
If, on the other hand, you want to hold polygons in a type that spans both stages of the polygon lifecycle, it becomes
difficult to do this with an eye on immutability.
One solution is the use of an interface that is implemented both by the builder and the immutable type.
The FirstThen type can also assist in this situation: it holds an initial object (the first) until a state change occurs, and it is forced to hold a second object (the then). Once it is in the final state, it cannot change anymore. It is eventually immutable:
FirstThen to make a type eventually immutableclass PolygonManager {
// initially, the polygon is in builder phase
public final FirstThen<Polygon.Builder, Polygon> polygon =
new FirstThen<>(new Polygon.Builder());
// ...
public void construct() {
// in builder phase ...
polygon.getFirst().addPoint(point);
// transition
polygon.set(polygon.getFirst().build());
// from here on, polygon is immutable!
}
public Point firstPoint() {
return polygon.get().points.get(0);
}
}8.2. Definition
We propose a system of eventual immutability based on a single transition of state inside an object.
@ImmutableContainer(hc=true, after="frozen")
class SimpleImmutableSet1<T> {
private final Set<T> set = new HashSet<>();
private boolean frozen;
@Only(before="frozen")
public boolean add(T t) {
if(frozen) throw new IllegalStateException();
return set.add(t);
}
@Mark("frozen")
public void freeze() {
if(frozen) throw new IllegalStateException();
frozen = true;
}
@Only(after="frozen")
public Stream<T> stream() {
if(!frozen) throw new IllegalStateException();
return set.stream();
}
@TestMark("frozen")
public boolean isFrozen() { (1)
return frozen;
}
public int size() { (1)
return set.size();
}
}| 1 | These methods can be called any time. |
Each of the methods add, freeze and stream starts with a precondition on the field frozen, and one of them,
freeze, changes its own precondition: after it has run once, it can never run again.
That is the signature of a mark.
The rules are sufficiently general to support arbitrary preconditions, as shown in the following variant.
This example does not require an additional field, but relies on the empty/not-empty state change:
@ImmutableContainer(hc=true, after="set")
class SimpleImmutableSet2<T> {
private final Set<T> set = new HashSet<>();
@Mark("set")
public void initialize(Set<T> data) {
if(!set.isEmpty()) throw new IllegalStateException();
if(data.isEmpty()) throw new IllegalArgumentException();
set.addAll(data);
}
@Only(after="set")
public Stream<T> stream() {
if(set.isEmpty()) throw new IllegalStateException();
return set.stream();
}
public int size() {
return set.size();
}
@TestMark("set")
public boolean hasBeenInitialised() {
return !set.isEmpty();
}
}Let us summarize the annotations:
The
@Markannotation marks methods that change the state from before to after.The
@Onlyannotation identifies methods that, because of their precondition, can only be executed without raising an exception before (when complemented with abefore="…"parameter) or after (with aafter="…"parameter) the transition.The analyzer computes the
@TestMarkannotation on methods which return the state as a boolean. There is a parameter to indicate that instead of returningtruewhen the object is after, the method actually returnstrueon before.Finally, the eventuality of the type shows in the
after="…"parameter of@FinalFields,@Immutableor the shorthand@ImmutableContainer.
In each of these annotations, the value of the … in the after= or before= parameters is a label that names the
transition.
A computed label is the name of the field that guards the transition; in case there are multiple fields involved,
their names are represented in a comma-separated fashion.
A contract on a type without fields, such as an interface, chooses a name.
Either way, the @Mark , @Only and after= annotations of one transition carry the same label.
The @Mark and @Only annotations can also be assigned to parameters, in the event that marked methods are called
on a parameter of eventually immutable type.
Consider the following utility method for EventuallyFinal, frequently used in the analyzer’s own code:
EventuallyFinalpublic static <T> void setFinalAllowEquals(
@Mark("isFinal") EventuallyFinal<T> eventuallyFinal, T t) {
if (eventuallyFinal.isVariable() || !Objects.equals(eventuallyFinal.get(), t)) {
eventuallyFinal.setFinal(t);
}
}Here, the setFinal method’s @Mark annotation travels to the parameter, where it is applied to the argument each
time the static method is applied.
8.3. Propagation
The support types detailed in Support classes can be used as building blocks to make ever more complex eventually
immutable classes.
Effectively final fields of eventually immutable type will at some point hold objects that are in their final or after
state, in which case they act as immutable fields.
The analyzer itself consists of many eventually immutable classes; we show some examples in Support classes in the analyzer.
| For everyday use of eventual immutability, this is probably the most important consequence of all definitions up to now. |
8.4. Before the mark
A method can return an eventually immutable object, guaranteed to be in its initial or before state.
This can be annotated with @BeforeMark .
Employing SimpleImmutableSet1 from the example above,
@BeforeMark annotation@BeforeMark
public SimpleImmutableSet1 create() {
return new SimpleImmutableSet1();
}Similarly, the analyzer can compute a parameter to be @BeforeMark , when in the method, at least one before-mark
method is called on the parameter.
Finally, a field can even be @BeforeMark , when it is created or arrives in the type as @BeforeMark , and stays in
this state.
This situation must occur in a type with a @Finalizer (Finalizers).
8.4.1. Finalizers in the before state
A finalizer lets a type hold an eventually immutable object in its before state, and hand it over at the end of its own life-cycle. Let us start from the following example, using EventuallyFinal:
@Finalizer methodclass ExampleWithFinalizer {
@BeforeMark
private final EventuallyFinal<String> data = new EventuallyFinal<>();
@Fluent
public ExampleWithFinalizer set(String string) {
data.setVariable(string);
return this;
}
@Fluent
public ExampleWithFinalizer doSomething() {
System.out.println(data.toString());
return this;
}
@Finalizer
@BeforeMark
public EventuallyFinal<String> getData() {
return data;
}
}Using @Fluent methods to go from construction to finalizer is definitely allowed according to the rules:
@ImmutableContainer
public static EventuallyFinal<String> fluent() {
EventuallyFinal<String> d = new ExampleWithFinalizer()
.set("a").doSomething().set("b").doSomething().getData();
d.setFinal("x");
return d;
}Passing on these objects as arguments is permitted, but the recipient should not call the finalizer. Actually, given our strong preference for containers, the recipient should not even modify the object! Consider:
@ImmutableContainer
public static EventuallyFinal<String> stepWise() {
ExampleWithFinalizer ex = new ExampleWithFinalizer();
ex.set("a");
ex.doSomething();
ex.set("b");
doSthElse(ex); (1)
EventuallyFinal<String> d = ex.getData();
d.setFinal("x");
return d;
}
private static void doSthElse(@NotModified ExampleWithFinalizer ex) {
ex.doSomething(); (2)
}| 1 | here we pass on the object |
| 2 | forbidden to call the finalizer; other methods allowed. |
The first rule of Sequencing rules allows you to store a finalizer type inside a field, but only when finalization is attached to the destruction of the holding type.
Processors and finishers
Finalizers allow us to introduce the concepts of processors and finishers for eventually immutable types in their before state.
The purpose of a processor is to receive an object in the @BeforeMark state, hold it, use a lot of temporary data in the meantime, and then release it again, modified but still in the @BeforeMark state.
class Processor {
private int count; (1)
@BeforeMark (2)
private final EventuallyFinal<String> eventuallyFinal;
public Processor(@BeforeMark EventuallyFinal<String> eventuallyFinal) {
this.eventuallyFinal = eventuallyFinal;
}
public void set(String s) { (3)
eventuallyFinal.setVariable(s);
count++;
}
@Finalizer
@BeforeMark (4)
public EventuallyFinal<String> done(String last) {
eventuallyFinal.setVariable(last + "; tried " + count);
return eventuallyFinal;
}
}| 1 | symbolizes the temporary data to be destroyed after processing |
| 2 | the field is private, not passed on, no @Mark method is called on it, and it is exposed only in a @Finalizer |
| 3 | symbolizes the modifications that act as processing |
| 4 | the result of processing: an eventually immutable object in the same initial state. |
The purpose of a finisher is to receive an object in the @BeforeMark state, and return it in the final state.
In the meantime, it gets modified (finished), while there is other temporary data around.
Once the final state is reached, the analyzer guarantees that the temporary data is destroyed by severely limiting the scope of the finisher object.
class Finisher {
private int count; (1)
@BeforeMark (2)
private final EventuallyFinal<String> eventuallyFinal;
public Finisher(@BeforeMark EventuallyFinal<String> eventuallyFinal) {
this.eventuallyFinal = eventuallyFinal;
}
@Modified
public void set(String s) { (3)
eventuallyFinal.setVariable(s);
count++;
}
@Finalizer
@ImmutableContainer (4)
public EventuallyFinal<String> done(String last) {
eventuallyFinal.setFinal(last + "; tried " + count);
return eventuallyFinal;
}
}| 1 | symbolizes the temporary data to be destroyed. |
| 2 | only possible because the transition occurs in a @Finalizer method |
| 3 | symbolizes the modifications that act as finishing |
| 4 | the result of finishing: an eventually immutable object in its end-state. |
8.5. Ownership and eventual immutability
Eventual immutability is a property of a type: every instance goes through the same transition, and the mark and
the before-only methods are part of the type’s API.
Freshness and ownership are properties of a reference, at a point in the program: this object has exactly one
holder.
The two meet because a single holder is what makes modification safe, and the moment that holder stops being the
only one is a natural mark.
Pony’s iso becoming val, Rust’s &mut becoming &, and C#'s isolated objects becoming immutable all rely on
this: what only you hold, you may modify; once you stop modifying it, it may be shared as immutable.
Handing over instead of copying.
A type that stores a mutable object it receives is immutable only if nobody else can modify that object.
The builder of Eventual immutability's first example guarantees it with a copy, List.copyOf(points).
Ownership guarantees it without one, when every caller hands the object over (Transfer): what only the
new object holds, only the new object can modify.
public final class Palette {
private final List<String> colors;
private Palette(List<String> colors) { (1)
this.colors = colors;
}
public static Palette of(String... names) {
List<String> list = new ArrayList<>();
for (String name : names) list.add(name);
return new Palette(list); (2)
}
public String color(int i) {
return colors.get(i);
}
}| 1 | Private: of is the only caller. |
| 2 | The list is handed over: colors is @Owned . |
Compare the variants of Palette:
| Constructor | Type | colors owned |
|---|---|---|
private, stores the list (as above) |
| yes |
private, stores |
| yes |
private, stores |
| no |
public, stores the list |
| only in a closed world |
public, stores |
| only in a closed world |
With a private constructor, immutability needs no help: no code outside the type can pass the list, so the type is
independent of it.
The third row is the classical copy: safe, but List.copyOf may return its argument, so nothing can be said about
who holds the result.
With a public constructor, immutability needs ownership.
In a closed world (Transfer), every call site is known; when each of them hands its list over,
colors is @Owned .
A parameter handed over into an owned field is no dependence, since its caller holds the object no more: rule 3 of
Immutability is satisfied, and the type is immutable after construction, with neither a copy nor a mark.
One caveat keeps this honest: what the list contains, the caller may still hold.
For the elements, it is independence that counts, as before.
A List<Counter> of mutable Counter objects that the caller passed in keeps the type dependent, handed over or not.
An unmodifiable view over a list handed over is owned too: the view is a new object that holds the list and nothing else, so the field reaches both, and nobody else reaches either (Owned fields).
Checking the before state. An eventually immutable object in its before state is safe only as long as its holders agree on the order of the calls. A fresh or owned object reaches its mark with a single holder, so the transition is safe by construction. A before-only method called on an object that is neither fresh nor owned is where the mark’s precondition can be broken from elsewhere: a candidate for a warning.
Finalizers as the bridge.
A builder whose build() is a @Finalizer hands its owned fields over to the result (Handing over what you own).
Once the builder is gone, the result holds the only references, and if it never modifies them, it is immutable from
birth.
This reaches the outcome of eventual immutability, a mutable phase followed by an immutable result, through a
transfer instead of a mark: two objects in sequence rather than one object changing state.
It is also how a translation into Rust would express it.
8.6. Extensions of annotations
When a type is eventually @FinalFields , should the field(s) of the state transition be marked @Final ?
Similarly, when a type is eventually immutable, should the analyzer mark the initially mutable or assignable fields
@Modified or @NotModified?
Basically, we propose to mark the end state, qualifying with the parameter after:
| property | not present | eventually | effectively |
|---|---|---|---|
finality of field | no annotation, or |
|
|
non-modification of field |
|
|
|
Since in an IDE it is not too easy to have multiple visual markers, it seems best to use the same visuals as the end state.
When a type is effectively @FinalFields (not eventually), all fields are effectively final.
The analyzer wants to emphasize the rules needed to obtain (eventual) immutability, by clearly indicating which fields
break the immutability rules.
Eventual finality simply adds a @Final(after="mark") annotation to each of these situations.
8.7. Frameworks and contracts
A fair number of Java frameworks introduce dependency injection and initializer methods. This concept is, in many cases, compatible with the idea of eventual immutability: once dependency injection has taken place, and an initializing method has been called, the framework stops intervening in the value of the fields.
It is therefore not difficult to imagine, and implement in the analyzer, a before state (initialization still ongoing)
and an after state (initialization done) associated with the particular framework.
The example below shows how this could be done for the Verticle interface of the vertx.io framework.
Verticle.java and AbstractVerticle.java@FinalFields(after="init")
interface Verticle {
@Mark("init")
void init(Vertx vertx, Context context);
@Only(after="init")
Vertx getVertx();
@Only(after="init")
void start(Promise<Void> startPromise) throws Exception;
@Only(after="init")
void stop(Promise<Void> stopPromise) throws Exception;
}
public abstract class AbstractVerticle implements Verticle {
@Final(after="init")
protected Vertx vertx;
@Final(after="init")
protected Context context;
@Override
public Vertx getVertx() {
return vertx;
}
@Override
public void init(Vertx vertx, Context context) {
this.vertx = vertx;
this.context = context;
}
...
}9. Modification, part 2
This section goes deeper into modification, dependence and independence. We start with cyclic references.
9.1. Cyclic references
We need to study the situation of seemingly non-modifying methods with modified parameters.
Up to now, a method is only modifying when it assigns to a field, calls a modifying method on one of the fields, or directly calls a modifying method on this.
However, there could be indirect modifications, as in:
@ImmutableContainer(hc=true)
public class CyclicReferences {
// not @FinalFields, not @Container
static class C1 {
// variable
private int i;
@Modified
public int incrementAndGet() {
return ++i;
}
@Modified (1)
public int useC2(@Modified C2 c2) {
return i + c2.incrementAndGetWithI();
}
}
@FinalFields // not @Container
static class C2 {
private final int j;
@Modified
private final C1 c1;
public C2(int j, @Modified C1 c1) {
this.c1 = c1;
this.j = j;
}
@Modified
public int incrementAndGetWithI() {
return c1.incrementAndGet() + j;
}
}
}| 1 | useC2 does not directly modify i, but incrementAndGetWithI does so indirectly. |
This observation forces us to tighten the definition of a non-modifying method: on top of the definition given above, we have to ensure that none of the modifying methods called on a parameter which is @Modified , call one of 'our' modifying methods.
These rules are mostly, but not easily, enforceable when all code is visible.
An additional interface can help to remove the circular dependency between the types. This has the advantage of simplicity, both for the programmer and the analyzer. It imposes more annotation work on the programmer, however, because the interface’s methods need contracts.
9.2. How to compute dependence
To compute dependence, the analyzer tracks actual objects, with the aim of knowing whether a field shares an object with another field or with a parameter. It computes a graph of variables depending on other variables, with the following four basic rules:
Note that saying v depends on a is the same as saying that the return value of method depends on some field inside A, the type of a.
This is especially clear when a == this.
We discern a number of special cases:
When
vis of a type that is immutable without hidden content, such as a primitive orjava.lang.String, there is nothing to share:vis independent ofaandb.If
bis of such a type,vis independent ofb.When the type of
vis immutable with hidden content, such as an unbound type parameter orjava.lang.Object,vshares at most hidden content withaandb: it is independent with hidden content.When
methodhas the annotation@Independent,vis independent ofa; with@Independent(hc=true), it shares at most hidden content witha.
When
bis of a type that is immutable without hidden content,vis independent ofb.If
Ais@Immutable, thenvis not dependent onb, because all its constructor parameters are independent, with or without hidden content.When the parameter has been marked
@Independent,vis independent ofb; with@Independent(hc=true), it shares at most hidden content withb.
This situation is similar to that of the constructor (rule 3), with a taking the role of v.
Most of the other computations are consequences of the basic rules above. For example,
in an assignment
v = condition ? a : b,vdepends on bothaandb.type casting does not prevent dependence: in
v = (Type)w,vdepends onwa pattern variable
pin an instance-of statementa instanceof P pdepends onaBinary operators return primitives or
java.lang.String: inv = a + b,vis independent ofaandb.
Note: in a method call v = a.method(b, c, d), dependence between b, c, and d is possible.
It is covered by the @Modified annotation:
when a parameter is @NotModified, no modifications at all are possible, not even indirectly.
Dependence between parameters can be computed like any other (The link system); we nevertheless advocate the use of containers: all parameters should be @NotModified.
On methods without a body, extra parameters to the annotation let the user contract it.@Independent
9.3. Locally implemented abstract methods
Abstract methods are present in interfaces, and abstract classes. Their very definition is that no implementation is present at the place of definition: only the ins (parameters) and outs (return type) are pre-defined.
Functional interfaces are interfaces with a single abstract method; any other methods in the interface are required to have a default implementation.
The following table lists some frequently used ones:
| Name | single abstract method (SAM) |
|---|---|
|
|
|
|
|
|
|
|
|
|
It is important not to forget that any interface defining a single abstract method can be seen as a functional interface. While the examples above all employ generics (more specifically, unbound type parameters), generics are not a requirement for functional interfaces. The Java language offers syntactic sugar for functional programming, but the types remain normal Java types.
We make one distinction between a functional interface and any other abstract type: the intention to hold data.
An interface that declares that it has no such intention, by being part of java.util.function or by carrying the annotation @FunctionalInterface, is a function type ([function-types]).
Every other interface with a single abstract method is an abstract type like any other.
In this section we want to discuss a limited application of functional interfaces: the one where the SAMs have a local implementation. The general case, where objects of abstract types come in via a parameter, will be addressed in More on hidden content. Consider the following example:
@FinalFields @Container
class ApplyLocalFunctions {
@Container
static class Counter {
private int counter;
@Modified
public int increment() {
return ++counter;
}
}
@Modified (1)
private final Counter myCounter = new Counter();
@Modified (2)
private final Supplier<Integer> getAndIncrement = myCounter::increment;
@Modified
private final Supplier<Integer> explicitGetAndIncrement = new Supplier<Integer>() {
@Override @Modified
public Integer get() {
return myCounter.increment();
}
};
@Modified
public int myIncrementer() {
return getAndIncrement.get();
}
@Modified
public int myExplicitIncrementer() {
return explicitGetAndIncrement.get();
}
}| 1 | Modified in getAndIncrement and explicitGetAndIncrement |
| 2 | @Modified because its modifying method get is called in myIncrementer |
The fields getAndIncrement and explicitGetAndIncrement hold instances of anonymous inner classes of
ApplyLocalFunctions: these inner classes hold data, they have access to the myCounter field.
Their concrete implementations of get each modify myCounter.
A straightforward application of the rules of modification of fields makes getAndIncrement and
explicitGetAndIncrement @Modified :
in myIncrementer, a modifying method is applied to getAndIncrement, and in myExplicitIncrementer, a modifying method is applied to explicitGetAndIncrement.
Given that ApplyLocalFunctions is clearly @FinalFields , and the inner classes hold no other data, the inner classes are @FinalFields as well.
Now, if we move away from suppliers, but use consumers, we can discuss:
class ApplyLocalFunctions2 {
@Container
static class Counter {
private int counter;
@NotModified
public int getCounter() {
return counter;
}
@Modified
public int increment() {
return ++counter;
}
}
@NotModified
private final Counter myCounter = new Counter();
@Immutable (1)
private static final Consumer<Counter> incrementer = Counter::increment;
@Immutable
private static final Consumer<Counter> explicitIncrementer = new Consumer<Counter>() {
@Override
@NotModified
public void accept(@Modified Counter counter) { (2)
counter.increment();
}
};
@ImmutableContainer (3)
private static final Consumer<Counter> printer = counter ->
System.out.println("Have " + counter.getCounter());
@ImmutableContainer
private static final Consumer<Counter> explicitPrinter = new Consumer<Counter>() {
@Override
@NotModified
public void accept(@NotModified Counter counter) { (4)
System.out.println("Have " + counter.getCounter());
}
};
private void apply(@Container(contract = true) Consumer<Counter> consumer) { (5)
consumer.accept(myCounter);
}
public void useApply() {
apply(printer); // should be fine
apply(explicitPrinter);
apply(incrementer); // should cause an ERROR (6)
apply(explicitIncrementer); // should cause an ERROR
}
}| 1 | The anonymous type is static, has no fields, so is @Immutable .
It is not a container.
This is clearly visible in the explicit variant… |
| 2 | Here we see why incrementer is not a container: the method modifies its parameters. |
| 3 | Now, we have a container, because the anonymous type does not modify its parameters. |
| 4 | Explicitly visible here in explicitPrinter. |
| 5 | If we insist that all parameters are containers, … |
| 6 | We can use the annotations to detect errors.
Here, incrementer is not a container. |
Using the @Container annotation in a dynamic way allows us to control which abstract types can use the method:
when only containers are allowed, then the abstract types must not have implementations which change their parameters.
10. More on hidden content
In this section, we consider modifications to the hidden content of a type, and explain when they are of importance.
10.1. Visitors
Let’s go back to NonEmptyImmutableList, first defined in Abstract methods:
NonEmptyImmutableList@ImmutableContainer
interface NonEmptyImmutableList<T> extends HasSize {
// contracted: @NotModified, see the section on abstract methods
@Independent(hc=true)
T first();
// contracted: @NotModified
void visit(@Independent(hc=true) Consumer<T> consumer);
@NotModified
@Override
default boolean isEmpty() {
return false;
}
}We start the discussion with the following immutable implementation of this interface:
NonEmptyImmutableList@ImmutableContainer(hc=true)
class ImmutableOne<T> implements NonEmptyImmutableList<T> {
private final T t;
public ImmutableOne(@Independent(hc=true) T t) {
this.t = t;
}
@Override
public int size() {
return 1;
}
@Override
public T first() {
return t;
}
@Override
public void visit(Consumer<T> consumer) {
consumer.accept(t);
}
}According to the interface contract, we need the visit method to be non-modifying,
and also not to modify its parameter consumer.
However, following the normal definitions of modification, the following two statements hold:
Because
acceptis@Modified, we should mark the parameterconsumeras@Modified.Because
t, the parameter ofaccept, is@Modified, we should markvisitas@Modified.
The result of the first statement would violate the @Container property on ImmutableOne, and we’d be very
reluctant to do that:
according to the intuitive definition in Containers, ImmutableOne is a type that holds data, but does not
change the data it has been given.
This statement still holds in the presence of a visit method, which is nothing but a way of exposing the object
in a way similar to the method first.
The second statement would make visit modifying, which again goes against our intuition:
looping over elements is, in itself, not modifying.
Luckily, there are two observations that come to the rescue.
First, we believe it is correct to assume that concrete implementations of Consumer are semantically
unrelated to ImmutableOne.
As a consequence, we could say that the only modifications that concern us in this visit method, are the
potential modifications to accept 's parameter t.
Other modifications, for example those to the fields of the type in which the implementation is present,
may be considered to be outside our scope.
However, if we replace Consumer by Set and accept by add, we encounter a modification that we really do not
want to ignore, in an otherwise equal setting.
Therefore, it does not look like we can reason away potential modifications by accept.
We will have to revert to a contracted @IgnoreModifications annotation on the parameter consumer,
if we want to avoid ImmutableOne losing the @Container property.
While we will ignore this second source of modification in the ImmutableOne type,
we will defer or propagate it to the place where a concrete implementation of the consumer is presented.
We can ignore it here, because t is part of the hidden content of the type; what happens to
its content happens outside the zone of control of ImmutableOne.
The fact that it is passed as an argument to a method of consumer is reflected by the @Independent(hc=true) annotation.
It will take care of the propagation of modifications from the concrete implementation into the hidden content.
This results in the following annotations for visit in ImmutableOne:
visit method in ImmutableOne, fully annotated@NotModified
public void visit(@IgnoreModifications @Independent(hc=true) Consumer<T> consumer) {
consumer.accept(t);
}Note that we assume that we will need @IgnoreModifications for almost every use of a functional interface
from the package java.util.function occurring as a parameter.
These types are for generic use; one should never use them to represent some specific data type where modifications
are of concern to the current type.
Therefore, we make this annotation implicit in exactly this context.
A parameter of function type is implicitly @IgnoreModifications , on every method, with or without a body,
unless it is annotated @Modified . |
An interface that merely has a single abstract method, such as Iterable or Comparable, is not a function type:
nothing says that it does not hold data.
What the function does to its argument is not ignored.
It is deferred to the place where a concrete function is supplied, as the next section shows.
Looking at the more general case of a forEach implementation iterating over a list or array, we therefore end up with:
forEach implementation@NotModified
public void forEach(@Independent(hc=true) Consumer<T> consumer) {
for(T t: list) consumer.accept(t);
}Modifications to the parameter, made by the concrete implementation, are propagated into the hidden content of list,
as shown in the next section.
The @Independent(hc=true) annotation appears because hidden content in list is exposed to the consumer parameter.
This annotation does not appear for the accessible content of the immutable type.
Recall that parameters of modifiable type can already be shielded from external modification by
the @Independent annotation.
10.2. Propagating modifications
Let us apply the visit method of NonEmptyImmutableList to StringBuilder:
visitstatic void print(@NotModified NonEmptyImmutableList<StringBuilder> list) {
list.visit(System.out::println); (1)
}
static void addNewLine(@Modified NonEmptyImmutableList<StringBuilder> list) {
list.visit(sb -> sb.append("\n")); (2)
}| 1 | Non-modifying method implies no modification on the hidden content of list. |
| 2 | Parameter-modifying lambda propagates a modification to list 's hidden content. |
It is the second method, addNewLine, that is of importance here.
Thanks to the @Modified annotation, we know of a modification to list.
It may help to see the for-loop written out, if we temporarily assume that we have added an implementation of
Iterable to NonEmptyImmutableList, functionally identical to visit:
addNewLinestatic void addNewLine(@Modified NonEmptyImmutableList<StringBuilder> list) {
for(StringBuilder sb: list) {
sb.append("\n");
}
}Note that while NonEmptyImmutableList is immutable, its concrete instantiation gives access to a modifying method
in its hidden content.
We really need to know that sb is part of the hidden content of list for the modification on sb to propagate to list.
Without this propagation, we would not be able to implement the full definition of modification of parameters,
as stipulated in Modification, in this relatively straightforward and probably frequently occurring situation.
Moving from NonEmptyImmutableList to NonEmptyList, defined here, which has a modifying method,
allows us to contrast two different modifications:
sb to that on liststatic void addNewLine(@Modified(hc=true) NonEmptyList<StringBuilder> list) {
list.visit(sb -> sb.append("\n")); (1)
}
static void replace(@Modified NonEmptyList<StringBuilder> list) {
list.setFirst(new StringBuilder("?")); (2)
}| 1 | Modification to the hidden content of list |
| 2 | Modification to the modifiable content of list |
The two modifications differ in what the caller has to fear.
After replace, the list holds a different object; after addNewLine, it holds the same objects as before, and one
of them has changed.
The definition of modification in Modification speaks of the entire object graph, and makes no difference between
the two.
We therefore add a second, finer verdict beside it:
The structural verdict follows the same propagation as modification, except that a modification reaching a variable
only through its hidden content — an element of a collection, an object of type parameter type — does not count.
A caller sees the difference: the argument of addNewLine is modified in its hidden content, that of replace in
its own state.
On a declaration without a body, the same annotation is a contract: an interface or annotated API can state that a
method touches only the elements of its argument.
To a reader of Java, this is the distinction between a List whose elements change and a list that itself changes.
To a translation into Kotlin, it is the choice between List and MutableList.
10.2.1. Elements of a concrete type
In NonEmptyList<StringBuilder>, the elements are hidden content because T is the list’s own type parameter.
Elements can also be of a concrete type that the owner names.
By the definition of Accessible and hidden content, and the example of Counters there, those are accessible content,
not hidden content.
Which of the two a modified object is, decides the structural verdict.
class Node {
int mark;
final List<Node> children = new ArrayList<>(); // Node is a concrete type that Node names
Node first; // may alias one of the children
void clear() { mark = 0; }
}
class Leaf {
int mark;
final List<Leaf> children = new ArrayList<>(); // as Node, without the field 'first'
void clear() { mark = 0; }
}
class Box<T> {
final List<T> items = new ArrayList<>(); // T is Box's own type parameter: hidden content
T first;
}
static void clearChildren(Node node) { for (Node c : node.children) c.clear(); } (1)
static void clearFirst(Node node) { node.first.clear(); } (2)
static void clearList(List<Node> nodes) { for (Node c : nodes) c.clear(); } (3)
static void clearBox(Box<Node> box) { for (Node c : box.items) c.clear(); } (4)
static void addChild(Node node) { node.children.add(new Node()); } (5)
static void clearLeaves(Leaf leaf) { for (Leaf c : leaf.children) c.clear(); } (6)The verdicts on the parameters are:
| Parameter | Deep | Structural |
|---|---|---|
(1) | modified | modified: a child may be |
(2) | modified | modified |
(3) | modified | not modified: the list itself only changes in its elements |
(4) | modified | not modified: to |
(5) | modified | modified |
(6) | modified | modified |
(1) and (2) can write to the same object (
node.first == node.children.get(0)), so one cannot be structural and the other not:Node.firstmakes aNodeaccessible content of aNode, and a modified child may be that object.(6), the same code without
first, is structural as well. To the list, its elements are hidden content; but it wasLeafthat wroteList<Leaf>, so to aLeafits children areLeafobjects, accessible content, asCountersof Accessible and hidden content sees theCounterobjects in its map.(3) versus (4): in (3) the parameter is the list itself, and to a list its elements are hidden content. In (4) the instantiation
Box<Node>is the caller’s, notBox’s: to `Box, the elements ofitemsare its type parameterT, and so is the fieldfirst.(3) is the case where a Kotlin programmer would write
List, and notMutableList, for the parameter.
The definition, with declared types
The examples show that we need to be precise about which objects are accessible content of a parameter p.
The definition of Accessible and hidden content goes by declared types. Applied to a parameter p:
The first point is why (1) and (2) above must agree: the method reached the child through the list, but the same
object can be reached through the field first.
The second point follows the reasoning of Accessible and hidden content: what a subclass adds is outside the control,
and outside the responsibility, of the code that sees only the parent type.
The third is the same reasoning from the other side: the type that chose Item for the elements of its list is in
control of them, as Counters is of its counters (CodeLaser/maddi-mod#159).
The paths can be longer than one field, as the next example shows.
class St { St parent; St first; final List<Edge> edges = new ArrayList<>(); final Set<Edge> labels = new HashSet<>(); }
class IfSt extends St { Edge ifedge; }
class Edge { St dest; boolean labeled; }
class Item { int n; void touch() { n++; } }
class Bag { final List<Item> items = new ArrayList<>(); }
static void lift(St s) { for (Edge e : s.edges) e.dest.labels.add(e); } (1)
static void reset(St s) { for (Edge e : s.edges) e.labeled = true; } (2)
static void resetIf(IfSt s) { for (Edge e : s.edges) e.labeled = true; } (3)
static void touchAll(Bag b) { for (Item i : b.items) i.touch(); } (4)| 1 | Structural. e.dest is a St, and a St is accessible content of s through s.parent and s.first, so the
write may be to the state of s.parent. |
| 2 | Structural. St wrote List<Edge>, so an edge in s.edges is accessible content of s. IfSt.ifedge plays no
part: only a subclass declares it, and to a St it is hidden content, even when s.parent is an IfSt at run time. |
| 3 | Structural, for the same reason, and because to an IfSt, ifedge is accessible content as well. |
| 4 | Structural. Bag wrote List<Item>: its items are accessible content of the bag. |
A static analyzer does not see the objects, only their types: it must decide whether a modified object may be accessible content of the owner. How maddi does that, and where it deviates from the definition, is described in Structural modification.
10.2.2. The step back to the elements
Modifications travel from the elements to their container; do they also travel back, from the container to the objects that were put into it? They should: an object put into a collection, and modified after it comes out again, is modified.
static String useLocal(@Modified Node input) {
List<Node> list = new LinkedList<>();
list.add(input);
for (Node c : list) c.clear(); (1)
return list.get(0).toString();
}| 1 | c may be input: a co-element of a modified element is modified. |
The modification of input is of the same kind as that of the element: clear() writes the element’s own field, and
when the element is input, that is input’s own state, so `input is modified structurally too, not only in its
hidden content.
An element modified only in its hidden content makes the co-element modified in its hidden content only.
The same reasoning applies when the modification of the elements happens in another method.
Applying the two methods addNewLine and replace further on:
addNewLine and replacestatic String useAddNewLine(@Modified StringBuilder input) { (1)
NonEmptyList<StringBuilder> list = new One<>();
list.setFirst(input);
addNewLine(list);
return list.first().toString();
}
static String useReplace(@NotModified StringBuilder input) {
NonEmptyList<StringBuilder> list = new One<>();
list.setFirst(input);
replace(list); (2)
return list.first().toString();
}| 1 | The third statement modifies the hidden content of list, as @Modified(hc=true) on addNewLine says, and
input is part of that hidden content. |
| 2 | This action discards input from list without modifying it. |
The step through a call, as in useAddNewLine, is the harder one for an analyzer; see Where the analyzer deviates from the definitions.
Finally, we mention again the modification to a field from a concrete lambda:
List<String> strings = ...
@Modified
void addToStrings(@NotModified NonEmptyList<StringBuilder> list) {
list.visit(sb -> strings.add(sb.toString()));
}10.3. Content dependence
Going back to ImmutableOne, we see that the constructor assigns the parameter t to the instance’s field.
Let us call this sharing of hidden content between a parameter and a field content dependence,
and mark it using @Independent(hc=true) :
ImmutableOneprivate final T t;
public ImmutableOne(@Independent(hc=true) T t) {
this.t = t;
}Returning a part of the hidden content of the type, or exposing it as argument, both warrant a @Independent(hc=true)
annotation:
ImmutableOne@Independent(hc=true)
@Override
public T first() {
return t;
}
@Override
public void visit(@Independent(hc=true) Consumer<T> consumer) {
consumer.accept(t);
}Observe that content dependence implies absence of dependence, as described in Dependence and How to compute dependence, exactly because we are dealing with type parameters of an immutable type.
Another place where content dependence can be seen, is the for-each statement:
Iterable<StringBuilder> list = ...;
List<StringBuilder> builders = ...;
for(StringBuilder sb: list) {
builders.add(sb);
}Because the Collection API contains an add method annotated as:
add in Collection annotated@Modified
boolean add(@Independent(hc=true) E e);indicating that after calling add, the argument will become part of the hidden content of the collection,
we conclude that the builders list becomes content dependent on the local loop variable sb.
Similarly, this loop variable contains hidden content from the list object.
Let us look at a possible implementation of Collection.addAll:
addAll in Collection@Modified
boolean addAll(@Independent(hc=true) Collection<? extends E> collection) {
boolean modified = false;
for (E e : collection) if (add(e)) modified = true;
return modified;
}The call to add makes this content dependent on e.
Because e is also content dependent on collection, that parameter shares its hidden content with
the instance.
We are now properly armed to see how a for-each loop can be implemented using an iterator whose hidden content is shared with that of a container.
10.4. Iterator, Iterable, loops
Let us start with the simplest definition of an iterator, without remove method:
Iterator type, without remove method@Container
interface Iterator<T> {
@Modified
@Independent(hc=true)
T next();
@Modified
boolean hasNext();
}Either the next method, or the hasNext method, must make a change to the iterator, because it has to keep track
of the next element.
As such, we make both @Modified .
Following the discussion in the previous section, next is @Independent(hc=true) , because it returns part of the hidden
content held by the iterator.
The interface Iterable is a supplier of iterators:
Iterable type@ImmutableContainer
interface Iterable<T> {
@Independent(hc=true)
Iterator<T> iterator();
}First, creating an iterator should never be a modifying operation on a type.
Typically, as we explore in the next section, it implies creating a subtype, static or not, of the type implementing Iterable.
Second, the iterator itself is independent of the fields of the implementing type, but has the ability to return its hidden content.
The loop, on a variable list of type implementing Iterable<T>, is expressed as for(T t: list) { … }, and can be interpreted as
IteratorIterator<T> it = list.iterator();
while(it.hasNext()) {
T t = it.next();
...
}The iterator it is content dependent on list; via the next method, it hands the hidden content of the list to t.
10.5. Independence of types
A concrete implementation of an iterator is often a nested type, static or not (inner class), of the iterable type:
Iterator@ImmutableContainer(hc=true)
public class ImmutableArray<T> implements Iterable<T> {
private final T[] elements;
@SuppressWarnings("unchecked")
public ImmutableArray(List<T> input) {
this.elements = (T[]) input.toArray();
}
@Override
@Independent(hc=true)
public Iterator<T> iterator() {
return new IteratorImpl();
}
@Container
@Independent(hc=true)
class IteratorImpl implements Iterator<T> {
private int i;
@Override
public boolean hasNext() {
return i < elements.length;
}
@Override
public T next() {
return elements[i++];
}
}
}For ImmutableArray to be immutable, the iterator() method must be independent of the field elements, in other words, the IteratorImpl object must not expose the ImmutableArray 's fields to the outside world.
It cannot be immutable itself, because it needs to hold the state of the iterator.
However, it should protect the fields owned by its enclosing type, up to the same standard as required
for immutability.
We propose to add a definition for the independence of a type, identical to the "shielding off" part of the definition of immutability. Let’s first go there in a roundabout way:
Clearly, such external modifications are only possible when the constructor, method or field is non-private.
Armed with this definition, we can define the independence of types:
This definition is entirely equivalent to the definition of immutability without rules 0 and 1, and rules 2 and 3 restricted to those fields that are 'exposed' to the outside world via dependence or content dependence.
Consider the static variant of IteratorImpl, which makes it more obvious that IteratorImpl maintains a reference
to the element array of its enclosing type:
Iterator as a static nested type@ImmutableContainer(hc=true)
public class ImmutableArray<T> implements Iterable<T> {
...
@Container
@Independent(hc=true)
static class IteratorImpl<T> implements Iterator<T> {
private int i; // variable
private final T[] elements;
private IteratorImpl(T[] elements) {
this.elements = elements;
}
@Override
public boolean hasNext() {
return i < elements.length;
}
@Override
@Modified
public T next() {
return elements[i++];
}
}
}The type T is part of the hidden content, the T[] and the counter i are part of the accessible content.
No external modification can impact the array or the counter; indeed, only T and a boolean are exposed.
The latter is immutable, so does not allow modifications.
The former allows modifications on the hidden content, whence the @Independent(hc=true) annotation for IteratorImpl.
Immutable types are independent as a type, but a type does not even have to be immutable to be independent. In fact, any type communicating via immutable types to the outside world is independent:
@Independent
@Container
class GetterSetter {
private int i;
public int getI() {
return i;
}
public void setI(int i) {
this.i = i;
}
}The following table summarizes the relationship between immutability and independence by means of example types:
| Mutable, modifiable | Immutable with hidden content | Immutable without hidden content | |
|---|---|---|---|
Dependent | | ||
Independent with hidden content | | | |
Independent | | |
11. Nullability
Most of this document has been about one question: who can modify what?
The analyzer answers it by computing where objects flow — between fields, parameters, return values and the
hidden content of containers — and the chapters on Dependence and More on hidden content describe
that flow in terms of links.
null is a value like any other, and it flows along the same links.
This chapter asks another question the link engine can answer: where can null turn up?
Nullability is a standard topic for static analyzers, and we approach it from the computational side, as
we do immutability: the analyzer infers where null can be, and the user adds annotations only where
there is no code to infer from, on abstract methods and in the annotated APIs.
The verdicts have two applications.
The first is Java: @Nullable and @NonNull annotations, in the flavour of your choice, on fields,
parameters and return values.
The second is translation into a language whose type system has nullability built in: a Java String
becomes a Kotlin String or String?, and every dereference of a possibly-null value becomes ?.,
!! or ?:.
The same verdicts drive the C# translation’s nullable reference types.
11.1. Definitions
Every position that can hold a reference — a field, a parameter, a method’s return value, a local variable, and, as we will see, the elements of an array and the type arguments of a generic type — is in one of three states.
The third state is unspecified: nobody has said anything, and the analyzer does not claim anything.
Unspecified is not a synonym for nullable.
It is the state of a library method with no annotation and no source, of a type variable T outside its
instantiation, and of the outputs of a method the analyzer could not analyze.
What an unspecified position means to a consumer is a matter of reading: in the @NullMarked reading, which
the JSpecify annotations define and which Kotlin applies to its own code, an unannotated position is not
null, and only @Nullable is ever written.
The analyzer’s default output follows that reading.
Note the asymmetry between the first two definitions and the third. Nullable and not null are both claims about the program; unspecified is the absence of a claim. The analyzer’s job is to turn as many unspecified positions as it can into one of the two claims, and to be honest about the rest.
11.1.1. Content
A collection, a map, an array or a holder has content, and the content has a nullability of its own.
A List<String> that is never null may still hold null elements; a Map may have non-null keys and
nullable values.
The analyzer tracks one state per type argument, recursively, and one for the elements of an array.
We write them in Kotlin’s notation, which has a place for every one of them: Map<String, String?> is a
non-null map with non-null keys and nullable values; String?[] is a non-null array whose elements may be
null.
In Java, type-use annotations say the same (Map<String, @Nullable String>, @Nullable String[]).
The maddi annotations are declaration annotations, and summarize the content in two ways:
@NotNull(content=true)states that the value is not null, and neither is any of its content: nonullelements in the array or collection, nonullkeys or values in the map. This is the shape the annotated APIs use for factories such asList.ofandMap.of.@NotNull(nullableArguments={1})and its@Nullablecounterpart name the type arguments, by position, that may holdnull, one level deep; on an array type, position0stands for the elements. The annotated JDK writes this where JSpecify annotates a type argument:Collection.toArray()returns@NotNull(nullableArguments={0}) Object[], an array that is nevernullbut whose elements may be.
11.1.2. Contracts
On an abstract method, on an interface, and in the annotated APIs, a null annotation is a contract, as
every annotation in this document is in those positions.
A contract does two things.
A @Nullable contract is a seed: the analyzer takes the annotated position as a place where null can
come from, and follows it from there.
A @NotNull contract is a barrier: null does not travel through it.
A caller that passes null to a @NotNull parameter is in error, and the analyzer reports the call rather than
weakening the parameter.
The analyzer reads the null annotations of the common families as contracts — JSpecify, JetBrains, the
Checker Framework, JSR-305 and javax.annotation, Lombok’s @NonNull — including the scope of
@NullMarked and @NullUnmarked.
A library that is @NullMarked therefore needs no annotated API for its nullability.
The annotated APIs that ship with the analyzer carry the JDK’s nullability, generated from JSpecify’s
annotated JDK, down to the type arguments and array elements: Map.get may return null,
Map.of may not, Collection.toArray() may hold null elements.
11.2. What the analyzer computes
The analyzer computes nullability as reachability: it collects the places where null enters the program,
the seeds, and follows the links until nothing more is reached.
A position that is reached is @Nullable ; a position that is not reached is @NotNull , or unspecified where the
analyzer has no right to a claim.
The seeds are:
the literal
null, assigned, returned, passed as an argument, stored in an array or a collection;a field that can still hold Java’s default value: not final, no initializer, and not assigned by every constructor;
an array created without an initializer,
new String[n];a library method’s nullable result, by contract:
Map.get,Queue.poll,System.getProperty,BufferedReader.readLine, and their relatives;a
@Nullablecontract on a source declaration;and, by default, a parameter or field that the code itself compares with
null. The author ofif (key == null)expectsnullthere, even when no caller in sight passes it.
The links carry the seeds onward: from an argument to the callee’s parameter, from a return value to the variable that receives it, from a parameter or a local into a field, from a field into a return value, and along the override chain, where a parameter has one nullability for the whole chain and a return value may be narrowed by an override but not widened. An example:
class Registry {
private final Map<String, Entry> entries = new HashMap<>();
@Nullable
private Entry last; (1)
public void register(@NotNull String key, @NotNull Entry entry) { (2)
entries.put(key, entry);
last = entry;
}
@Nullable
public Entry find(@NotNull String key) { (3)
return entries.get(key);
}
@Nullable
public Entry last() { (4)
return last;
}
public int size(@Nullable String key) { (5)
Entry e = key == null ? last : find(key); (6)
return e == null ? 0 : e.size();
}
}| 1 | last is not final, has no initializer, and no constructor assigns it: it can hold Java’s default value. |
| 2 | No call in the program passes null here; see Who calls? for what that is worth. |
| 3 | The annotated JDK declares Map.get nullable; the result is returned directly. |
| 4 | The field’s null flows into the return value. |
| 5 | The parameter is compared with null: the author expects it. |
| 6 | find(key) is evaluated only where key is known not to be null, so nothing flows into find’s
parameter; the local `e is nullable, and the dereference e.size() is guarded. |
Callout 6 shows the second half of the computation.
Links are not path-sensitive — after if (x == null) x = "default"; the variable x still links to the
null — so the analyzer walks every method body a second time, in statement order, and records at each
statement which locals, parameters and fields of this are known not to be null there: after
if (v == null) return;, inside if (v != null) and in the else of v == null, after a dereference
v.m() (which would have thrown), after Objects.requireNonNull(v) or a null-check predicate such as
isNotBlank(v), after v = new X(), inside the right-hand operand of v != null && …, and in the branch
of ?: that the condition excludes null from.
An assignment forgets the fact; a loop, a try and a switch keep only the facts about variables they do
not assign; two branches that both continue keep what both established.
A link is then not followed where its source is known not to be null at the statement that makes it,
and an argument known not to be null carries nothing to the parameter.
class Cache {
@Nullable
private Map<String, Node> nodes; (1)
@NotNull
private Map<String, Node> nodes() {
Map<String, Node> m = nodes;
if (m == null) { (2)
m = new HashMap<>();
nodes = m;
}
return m; (3)
}
public int count(@NotNull Node node) { (4)
return node.children().size() + nodes().size();
}
}| 1 | Lazily created: the field holds null until the first call to nodes(). |
| 2 | The local m starts nullable, from the field. |
| 3 | On both paths out of the if, m is known not to be null: on one it was assigned a fresh map, on
the other the test excluded null. |
| 4 | The parameter is dereferenced on every path through the method: a precondition.
Whatever the caller passes, null throws. |
Finally, conclusions feed conclusions: a method whose return value no null reaches is a non-null value wherever
it is called, and so nothing flows on from its call sites.
The computation is therefore repeated; each round only shrinks what null reaches, so the rounds stop on their own.
The result is sound in the sense that every round over-approximates the real flow.
11.2.1. Content, computed
The content positions are computed by the same reachability, over the links the chapter on
More on hidden content introduced.
A null added to a list, list.add(null), lands in the list’s hidden content, the virtual field that
stands for its elements, and from there in the list’s first type argument; a null value put into a map
lands in its value slice; new String[n] seeds the array’s elements; reading an element, x = a[i] or
for (String s : list), carries the content’s nullability into the variable.
Wherever an array or a generic value flows, the content positions at both ends are tied: a List<String?>
assigned to a field makes the field’s type argument nullable too, because in Java and in Kotlin a generic
type is invariant in its arguments.
class Grid {
private final String[] cells = new String[9]; // String?[] (1)
private final List<String> history = new ArrayList<>(); // MutableList<String?> (2)
public void play(int cell, @NotNull String mark) {
cells[cell] = mark;
}
public void record(int cell) {
history.add(cells[cell]); (3)
}
@Nullable
public String at(int cell) { (4)
return cells[cell];
}
}| 1 | An array created without an initializer: its elements start out null. |
| 2 | The list’s elements are nullable, because of callout 3. |
| 3 | An element of cells is read and added to the list. |
| 4 | An element read: the return value is nullable. |
The one rule the analyzer adds on top of the links is for arrays that are filled before they are read:
T[] a = new T[n]; for (int i = 0; i < n; i++) a[i] = f(i); leaves no null behind, and the creation is
not a seed when the loop that follows it directly writes every element.
11.3. Who calls?
The verdict on a parameter depends on a question the code cannot answer: are the calls the analyzer sees
all the calls?
For an application analyzed together with its callers, they are, and a parameter that no call passes
null to is not null: this is the closed world, and the default.
For a library, they are not: its users are callers the analyzer never sees, and so is the JDK, which calls
back Comparator.compare and equals(Object) with whatever it likes.
In the open world, a parameter of a method that can be called from outside — public, or protected in an
extensible type, in a type reachable from outside — that no null reaches is left unspecified, and so is
every position it flows into.
The one exception is the precondition of the second example: a parameter that the body dereferences,
hands to a @NotNull parameter, or rejects with if (p == null) throw … on every normal path is not null
whoever the caller is, since a null argument throws anyway.
Preconditions are a fact about the program that is worth having on its own.
The analyzer computes them per override family — in a closed world, a call to an overridable method runs
some member of the family, so the position is a precondition only when every member with a body throws
there — and reports the calls that may pass null into one: that is where a NullPointerException comes
from.
11.4. Applications
For Java, the analyzer writes the verdicts as annotations in a flavour of your choice: JSpecify, JetBrains,
the Checker Framework, JSR-305, or the maddi annotations of this document.
Under the @NullMarked reading only @Nullable is written.
In the JSpecify flavour, the only one with an unmarked annotation, a method with an unspecified parameter or return
value is marked @NullUnmarked so that nothing is claimed by omission, and an unspecified field, which cannot be
unmarked on its own, is written @Nullable , the reading that is safe for whoever reads it.
A position that already carries a null annotation is a contract and is left alone.
For Kotlin and C#, the verdicts become the types: T or T?, Map<String, String?>, String?[].
The translation then has choices to make that the Java annotations do not have, because a Kotlin program
must compile.
Where a value is nullable only through a library contract — the result of Map.get, say — and is written
into a collection, the translation keeps the collection’s element type non-null and asserts at the write,
list.add(map.get(k)!!), rather than turning every later read of a List<X?> into a !!.
Where a local that null can reach is dereferenced unconditionally a few lines further down, the
translation asserts at the declaration, val block = blocks.getWithKey(j)!!, and the local is non-null
from there on.
Each such choice moves an exception, never removes one: the NullPointerException the Java program would
have thrown at the dereference is thrown at the write or at the declaration instead.
The translation reports every place where it made one.
11.5. Measuring it
Immutability has no external oracle; nullability does. A library that carries null annotations throughout, such as Guava, can be analysed with its annotations hidden, and the inferred verdicts compared with the ones its authors wrote. Two numbers must be kept apart, because they cost differently: unsafe, inferred not null where the authors say nullable, and noise, inferred nullable where the authors say not null. The second oracle is the compiler: a program translated to Kotlin either compiles or it does not, and its own tests either pass against the translated classes or they do not. The measurements are in Measurements.
Under the hood
12. The link system
The chapters up to now have spoken of dependence, and have mentioned links only as the analyzer’s record of where objects flow. This chapter describes, at a technical but hopefully still readable level, how links can be computed, and how the maddi analyzer does so. It is the first of two chapters that trade the tutorial style for a look under the hood; the concepts of the earlier chapters — modification, independence, accessible and hidden content — are assumed throughout.
12.1. Links, natures, and summaries
A link is a triple: (from, nature, to), where from and to are variables — in a broad sense that
includes fields of variables, array elements, and several synthetic kinds introduced below — and the
nature expresses how the two relate.
Where the earlier chapters distinguished only assignment, "dependent" and "independent with
hidden content", the engine works with a richer alphabet.
The natures that matter most, with the notation used in the analyzer’s own output:
| symbol | name | meaning, by example |
|---|---|---|
| identity | two spellings of the same variable |
| assigned from / to |
|
| is element of / contains |
|
| subset / superset |
|
| shares elements |
|
| field of / contains field / shares fields | field-level dependence |
| object-graph containment / overlap | the weakest, "somewhere in the object graph" relations |
Reciprocals normally appear in pairs: x ∈ list.§xs alongside list.§xs ∋ x.
A * after a variable means it is (or may be) modified at that point: box*.t.
The unit of exchange between methods is the method link summary: how a method’s
return value, parameters and receiver relate, plus which of them it modifies.
For example, the summary of void set(Box<X> box, X x) { box.set(x); }, a method that calls the setter of a
one-field holder, reads [0:box*.t←1:x*, 1:x*→0:box*.t] -→ -: parameter x is assigned into the field of
parameter box (the link and its reciprocal), both are marked modified, and there are no return-value links.
Summaries are computed once per method and then applied at every call site, translating the callee’s
formal this and parameters into the actual receiver and arguments.
12.2. Two field models: concrete fields and virtual fields
A link names a place inside a variable, and there are two ways to name such a place:
For types whose source the analyzer has parsed, the place is a real field:
box.t,pair.a,bb.t.t.For shallowly analyzed types — most of the JDK — no field is visible. Their contents are represented by virtual fields, written with a
§prefix:list.§xsfor a list’s elements,map.§kvsfor a map’s entries. A virtual field is exactly the hidden content of the chapter on More on hidden content, given a name so that links can point at it.
The distinction drives which natures appear: a one-field holder tends to produce assignment links
(←, →), a collection produces element links (∈, ∋, ~, ⊆).
Otherwise the shapes are identical, and this symmetry is heavily used in the test suite, which pins the
same relationship over a source type (Box<T>) and a JDK type (List<X>) side by side.
One virtual field deserves special mention: §m, the modification component.
It stands for "the mutable aspect of this object, wherever it lives", and lets the engine express that two
variables share their modification fate without committing to a structural claim.
12.3. From expressions to a method summary
The linking pipeline runs per method, statement by statement, expression by expression:
a preparatory analysis computes, per method, the variables, their assignments and reads;
the link computer walks the method body; every expression produces a small result: its primary links, links about other variables it touched, and the variables it modified;
at every method call, the callee’s summary is translated onto the call site — the central operation of the whole system. Formal parameters become arguments, the formal
thisbecomes the receiver (including through inheritance: a supertype’sthismaps to the same receiver), and the callee’s modification marks transfer to the actual variables;the accumulated links feed a per-method link graph on which a fixpoint closure runs (next section);
the method’s own summary is extracted from the closure, and becomes available to its callers.
Functional interfaces get their own machinery, because a lambda’s effect happens at a distance: the place
that captures x → box.set(x) is not the place that applies it.
The capture is wrapped into a synthetic functional-interface variable carrying the lambda’s links and
modifications; the application site — say list.forEach(consumer) — finds that variable and lifts the
lambda’s links onto the concrete receiver: the summary of forEach says "the receiver’s elements flow
into the consumer", and the lifting engine substitutes the lambda’s parameter by those elements.
When the lambda is not yet known (a method that merely receives a Consumer and applies it), the
application is recorded symbolically and resolved later, at the caller that supplies the concrete lambda.
Alternatives are linked apart and then joined: the then- and else-blocks of an if are each
linked from their own copy of the graph as it stood before the statement, and the graph after the statement is
the union of the states the blocks end in, plus the state before when there is no else.
An assignment is a strong update that erases its target’s edges, and linked into one shared graph the
else-block erased what the then-block had established.
The union is not re-closed, since a then-else composition describes no execution; a variable stays in an
assignment group (The shared-variable collapse) only when every alternative puts it there, and is otherwise evicted,
with an assignment edge to the group’s representative.
Switches, loops and try are linked sequentially.
12.4. The closure: facts, witnesses, and an incremental fixpoint
Links compose: from a ← b and b ∈ c.§xs follows a ∈ c.§xs.
Composition is defined by a binary operator on natures;
composing natures generally weakens them — a subset of an overlap is at best an overlap — and the
weakest results (≤, ∩) eventually compose to nothing, which keeps the closure finite.
The engine that computes this closure treats each link as a fact and works
incrementally: statements add facts, each new fact is propagated forward and backward against the existing
closure, and every derived fact carries a witness — the pair of facts it was composed from.
Witnesses earn their keep when facts are removed: when a modification invalidates a link (the ⊇→~
rewrite below), all facts whose witness chain rests on the removed fact must be recomputed, and only those.
This is what makes the engine incremental rather than recompute-the-world.
Two practical notes on this machinery:
Modification is destructive: calling
list.remove(..)aftercopy.§xs ⊆ list.§xswas established demotes the subset claim to~(shares elements) — the copy still shares content, but the neat containment no longer holds. The rewrite fires once, at the modification statement, and only for links the modified variable itself owns.Cycle protection: pathological code shapes (deeply mutually recursive accessors, decompiler-generated monsters) can make the closure explode. The graph walk carries a hard ceiling; hitting it abandons the source-level computation for that method and degrades to its shallow summary, keeping the element alive at reduced precision rather than crashing or grinding.
12.5. Null as a value in the link graph
The chapter on Nullability describes nullability as reachability over the links. Four things in the link engine make that possible. Only the provenance bit is inert for the modification analysis; keeping markers in the summaries changes them, so that, and the argument links, are off unless the nullability configuration asks for them:
nullenters the graph as any constant does: a constant marker variable (written$_ce0,$_ce1, … in the engine’s output) whose expression is the null literal.x = nullgivesx ← $_ce0;list.add(null)giveslist.§xs ∋ $_ce0.A marker composes only as something a variable is assigned from:
y ← xandx ← $ce0givey ← $_ce0, so a local that carries anullto the return value is seen. It never composes as a _member:∋is written for a read as for a write, and letting the marker through would makenullan element of every map anullwas merely read from. A container takes anullonly on a direct link from a literal argument.Under the nullability configuration, a return value whose only link is to a marker keeps it in the method summary —
[-] -→ find←$_ce0reads as:findmay returnnull— where the summary would otherwise be emptied, and every call site records the links of its arguments. Areturn nullthereby crosses the call, and an argument reaches the callee’s parameter.Every link carries a provenance bit: direct when the statement’s own evaluation inserted it — an assignment, a callee’s summary applied at the call site, a field or element access — and derived when the closure or the shared-variable reconstruction composed it. Modification does not need the distinction: it wants the alias-and-containment relation, which is symmetric, transitive and path-insensitive. Nullability wants provenance — which literal, call or variable flows into which position, at which statement — and reads the direct links. The bit lives in the run only: a summary decoded from stored results reads as direct.
The virtual fields name the content positions: list.§xs is the list’s type argument, the key and value
slices of map.§kvs are the map’s two, box.t is the holder’s T, and an array element a[i] is the
array’s.
That is how Map<String, String?> is a verdict and not a guess.
12.6. Reading the output
For the curious, the fastest way to build intuition is to read summaries off real methods. A few shapes:
X read(Box<X> box) { return box.get(); } [-] --> read←0:box.t
X get(List<X> list) { return list.get(0); } [-] --> get∈0:list.§xs
void add(List<X> l, X x) { l.add(x); } [0:l*.§xs∋1:x, 1:x∈0:l*.§xs] --> - MOD[0:l]
List<X> copy(List<X> l) { return new ArrayList<>(l); } [-] --> copy.§xs⊆0:l.§xs
int size(List<X> list) { return list.size(); } [-] --> - MOD[]0:/1: are parameter indices; MOD[..] lists the modified variables.
The last line is the pure case: nothing flows, nothing changes — and that, ultimately, is what the whole
system exists to prove.
13. Convergence: the iterating analyzer
The previous chapter described how links are computed for one method, given the summaries of the methods it calls. This chapter describes the layer above: how the analyzer orders the work, iterates it to a fixpoint, knows when it is done, and what it does when the code refuses to cooperate. Like the previous chapter, it is technical in nature. It describes the design of the iteration: what must hold for a result to be trusted, and why the work is organised the way it is. The particulars of the current engine (its classes, thread counts, switches and measurements) are in The engine.
13.1. Properties, and the discipline of writing them
Every conclusion the analyzer draws — a method is non-modifying, a field’s content is unmodified, a type is immutable at some level — is a property value attached to a method, field or type. Three rules govern them:
Values are written at most once per analysis, and always in the conservative-to-optimistic direction: an absent value means "not decided yet", never "assumed fine". A guarded overwrite facility exists for the few places that legitimately refine a value (cycle breaking, below), and it enforces monotonicity: a verdict may become more precise, never contradict itself. The one sanctioned exception is the modification cutover after the fixpoint (After the fixpoint: the reachability passes).
Undecided is a first-class state. An analyzer component that cannot conclude — because a field’s type is not yet decided, a supertype is still open, a callee’s summary is missing — returns "no value" and will simply be visited again.
Decisions are local, dependencies are explicit. The immutability of a type depends on its fields' finality and modification status, its methods' modification status, and its supertypes' immutability; each of those is itself a property, computed by its own component.
13.2. Ordering the work
Before iteration starts, the analyzer computes an analysis order from the call graph and the type hierarchy: methods before their callers where possible, subtypes and enclosing types grouped, fields between their initializers and their readers. Two prepared ingredients matter beyond ordering:
part of construction: the set of methods only reachable from constructors. Assignments there do not count against a field’s effective finality — the essence of the effectively-final rule of the chapter on Final fields. Note that assignments to a nested type’s fields may come from the enclosing type, a sibling type, or a lambda anywhere in the primary type; the computation scans the whole primary type.
shallow summaries for everything outside the parsed source: JDK and library types receive their properties from the annotated APIs (below) or conservative defaults.
Java being Java, the call graph has cycles — recursion, mutual recursion, callbacks — so a single pass in analysis order cannot suffice. Hence: iteration.
13.3. The iteration loop
The main loop repeatedly runs the per-element analyzers over the analysis order, counting property changes — the number of newly decided or refined values in the pass. The first pass visits everything; subsequent passes narrow to a worklist: only elements whose inputs changed in the previous pass are dirty and revisited, with dirty targets mapped to their enclosing analysis-order element.
The loop can run in parallel: elements of the analysis order that do not depend on each other can be processed at the same time. The write-once discipline is what makes this possible, but it does not make the result independent of scheduling by itself: a verdict that depends on whether a sibling was decided in the same pass or in the previous one can come out differently. Such shapes must be known, and must resolve to the conservative side.
13.4. Verification and certification
Reaching "no more changes" is necessary but not sufficient: a fixpoint reached through optimistic intermediate states could in principle rest on values that would not be re-derived from scratch. The loop therefore ends with verification passes: with all values frozen, every element is recomputed once more and the engine checks that nothing changes. A run that exits this way is certified: the published verdicts are a self-consistent fixpoint of the analysis functions, independent of the path that produced them.
13.5. Cycle breaking
Some clusters never decide on their own. The classic shape: type A’s immutability waits on field type B, whose immutability waits on a method whose modification verdict waits on A. Everyone is undecided, nobody moves, and the loop reaches its certification point with a residue of undecided types.
At exactly that point — quiescence, with undecided immutability remaining — the engine activates cycle breaking: one more full pass in which the blocked components are allowed to resolve their undecided inputs by strategy rather than waiting. The default strategy is pessimistic: a type whose supertype is still undecided concludes at final-fields level. One conclusion is enough to unblock the cluster; the breaking pass then lets the normal machinery draw its conclusions from it, and the loop re-certifies including them. Without it, a code base with many such clusters ends with most of its types undecided; with it, the positive verdicts (immutable, immutable with hidden content) appear.
Cycle breaking is deliberately conservative about the strength of what it concludes: a type whose deep immutability rests on a broken cycle is published at the hidden-content level rather than the full level, because the unbroken evidence is not there.
A second kind of residue is not a cycle at all, but a verdict that will never arrive: an external, unannotated type has no immutability value, any type holding a non-private field of such a type cannot conclude, and — since "has a field of an undecided type" closes transitively — the undecidedness cascades through the field graph. Test code, which touches unannotated framework types most, made up the bulk of the cluster. The breaking pass treats these the same way it treats blocked supertypes: a missing field or abstract-method verdict is resolved pessimistically, and the type concludes at final-fields level — field finality being the one thing the analysis has, at that point, already established on its own. The published result is deliberately weak, honestly arrived at, and — unlike an absent verdict — usable by every downstream consumer.
13.6. Annotated APIs as analysis hints
The analyzer ships curated property sets for the JDK — String is deeply immutable, Object is
immutable with hidden content, the collection interfaces are mutable, the functional interfaces carry
their link summaries — under the name analysis hints.
They are loaded after parsing, resolved against the compiled-types universe of the run, and pre-seed the
property store so that source-code analysis starts from knowledge rather than pessimism.
The difference is not cosmetic: without the hints, every path through a JDK type bottoms out in
"undecided", and the immutability side of the analysis barely concludes anything positive; with them, the
proving-ground code bases settle into full immutability distributions.
13.7. When code refuses to cooperate
A static analyzer that dies on the first pathological method is useless on real code. Fault tolerance has three tiers:
method-level containment: an exception while linking a method marks it degraded: it carries no links, counts as modifying, and its outputs are unspecified to the nullability pass — the element stays alive, pessimistically;
cycle protection with a tight ceiling: run-away closures are cut off early and fall back to the method’s shallow summary, at reduced precision;
guards at the boundaries: unrepresentable link shapes are skipped at the point of production, and every skip is a logged, countable event rather than a silent loss.
13.8. After the fixpoint: the reachability passes
Two conclusions are deliberately not computed inside the iteration: the propagation of modification along call chains deeper than the summaries carry it, and nullability. Both have the same shape — a seed, and a closure over the links — and both were tried inside the loop first. There, a value written in an early pass froze the optimistic answer (unmodified, not null) before the evidence against it had arrived, and the write-once discipline then kept it. They run instead as reachability passes over the converged link facts.
The modification pass is a cutover: it re-derives which methods, parameters and fields are modified from primitive evidence and the converged links, downgrades the frozen optimistic values it contradicts — the one place a verdict is allowed to get worse — freezes the three modification properties, clears the immutability, independence and container verdicts derived from them, and lets the loop re-derive and re-certify. A chain deeper than one round reaches takes another, up to a fixed safety bound.
The nullability pass is the one-shot one: complete facts, after the cutover, every value written once. The chapter on Nullability describes what it computes. Mechanically:
its nodes are the fields, parameters, return values and locals of the analyzed code, plus a node per type argument and per array element of each;
its seeds are the null literals, the fields that can hold their default value, the arrays created empty, the library results declared nullable, the nullable contracts, and by default the parameters and fields that the code compares with
null;its edges are the direct links of each method’s variable data, the argument links of each call site, and the override chains;
its guards are the per-statement facts of a forward walk over every method body — which variables are known not to be
nullwhere — and an edge is not taken where its source is guarded.
The pass runs in rounds.
A round trusts no analyzed method’s return value; the next round treats every return value the previous one
found unreached as a non-null value at its call sites, and drops the edges from those sites.
Dropping edges only shrinks what null reaches, so the trusted set grows monotonically; a round also hands
the next the preconditions it found, so that an argument to one is known not to be null after the call.
The verdicts go into the same property store as everything else, from where the Java decorator, the Kotlin and
C# printers and the IDE read them.
What the pass needs from the iteration is that the link engine keeps the null markers in the method summaries and records the argument links at every call. Both change the content of the summaries, and are therefore off unless nullability is asked for.
14. The analyzer today
The chapters of the first part define concepts, and show annotations as the definitions require them.
This chapter records where the current implementation, the modification analysis in the maddi-mod repository,
stands with respect to those definitions: what it computes, what it only reads as a contract, where it approximates,
and how it has been measured.
It is the one chapter of this document that is expected to go out of date; everything in it is a statement about
software, not about the concepts.
14.1. What is computed
| Annotations | Status | Remarks |
|---|---|---|
| computed | Contracts on methods without a body, and in the annotated APIs. |
| computed | The structural verdict, beside the deep one; a contract on a declaration without a body. With the approximations of Structural modification. |
| computed | On methods with source, by default. The analyzer records, per method, the set of types whose static state it modifies, its own included; the static side effect is the part of that set the method does not own. A contract on library methods. |
| contract | Implicit on parameters of function type ([function-types]), in the annotated APIs only.
The separation check of The confinement guard reports the warning |
| computed | A contract on the eleven |
dynamic type annotations | computed | With the machinery that propagates eventual immutability. |
| computed, behind a switch | By the ownership pass, see Switches. A hand-written |
| partly | Read as a contract; the rule that a finalizer does not modify its receiver (A finalizer does not modify) is implemented,
and much depends on it.
With the ownership pass on, the call sites of contracted finalizers are checked, and |
| computed by propagation | Read as contracts, and computed for types that hold fields of eventually immutable type, for classes and
interfaces alike.
The detection from preconditions, as in the two |
| not read | |
| computed | By the nullability pass, when the nullability configuration asks for it. |
| computed | |
| contract | Implies |
| not read | Defined in |
14.2. Switches
The ownership pass runs once the analysis has converged, at the point where the analyzer certifies its result.
One fact flows back into the analysis: a parameter that every caller hands over into an owned field is no dependence
(Ownership and eventual immutability), after which the analysis converges again.
Otherwise the pass only adds verdicts.
The IDE plugins and the MCP server always run it; on the command line and in the build plugins it is off by
default, and --ownership, or the environment variable OWNERSHIP, switches it on.
The closed world of Transfer is a setting: --closed-world, a plugin setting, or
OWNERSHIP_WORLD=closed.
In a closed world, the third condition for an owned field is also relaxed: a non-private field qualifies when no code
outside its primary type mentions it.
For nullability (Who calls?), the closed world is the default.
Nullability is one configuration switch, nullability: the link engine then keeps the null markers in the method
summaries and records the argument links at every call (Null as a value in the link graph).
For comparison runs, most non-default behaviours are reachable through environment gates.
PARALLEL=n sets the number of threads; NOFORK restores the sequential linking of the branches of an if;
NOACCESSIBLEREACH restores the comparison of Structural modification to the owner’s own fields;
MODREACH_ROUNDS bounds the rounds of the modification reachability pass, 10 by default.
14.3. The engine
The chapters on The link system and Convergence: the iterating analyzer describe the design. In the code of maddi-mod:
| In the text | In the code |
|---|---|
the preparatory analysis | module |
the link system, the method link summary | module |
the closure of the link graph |
|
the main loop |
|
the guarded overwrite |
|
a degraded method | property |
the modification reachability pass |
|
the nullability pass |
|
Parallelism. The loop uses a small thread pool: at most eight threads, two fewer than the machine has cores, and small runs stay sequential. The vast majority of verdicts are independent of scheduling. The known exception is a constructor whose modification verdict depends on whether a sibling was decided in the same pass; it is tracked, and resolves to the conservative side.
The worklist. On large code bases it typically collapses from tens of thousands of elements to a few hundred within two or three passes.
How changes to the engine are accepted. A set of open-source code bases, from a few thousand to fifty thousand elements, is kept certified and crash-free on the default configuration. Every change to the engine must reproduce byte-identical verdict dumps on at least one of them, and an optimization is accepted only when the dump is identical before and after: speed is never allowed to buy a change of verdict. The same gates that drive these comparisons (Switches) can disable the worklist, parallelism and cycle breaking, and dump the verdict fingerprint per element.
Scale. On current hardware the analyzer processes, certified, code bases in the range of 50,000 elements (methods, fields, types) in a few minutes, with linking dominating the cost.
14.3.1. The shared-variable collapse
The link system as described in The link system has a scaling problem. Consider a builder-style method that threads one object through many locals: every local is assigned from the previous one, every field of the object is reachable from every local, and the naive link set grows as (locals × fields × natures) — the part-of link explosion. On real code bases this reached hundreds of thousands of links for a single method.
The collapse introduces shared variables: an equivalence grouping of variables that provably denote the same runtime slot, in two tiers:
modification identity: variables linked by
≡on their§mcomponent — they share their modification fate exactly;assignment groups: chains of pure whole-object assignments (
a = b; c = a;) collapse into one group with a single representative.
The graph then stores edges against group representatives only. What used to be quadratic bookkeeping becomes one edge per relationship, and the closure runs on the collapsed graph.
The price is reconstruction: the method summary must be expressed in terms of the method’s real
parameters, fields and return value — not internal representatives.
At extraction time, representative-level facts are projected back onto the group members that matter,
guided by one master rule: direction.
Assignment direction within a group is preserved (the source of an assignment passes knowledge to the
recipient, never the reverse), field-level facts are re-homed onto each endpoint of an intra-group link
(setI ← this mirrors to setI.i ← this.i), and a redundancy pass removes links that are transitive
consequences of nearer hops.
The reconstruction techniques have their own catalogue in the module (sv-reconstruction-techniques.md); the
summary-level behaviour is pinned by the link test suite, which is the de-facto specification.
14.4. Where the analyzer deviates from the definitions
The examples of the first part are analysed by the tests of Tests that pin the examples; the deviations below that concern an example are marked as such in the test.
14.4.1. Immutability
Countersin Accessible and hidden content is computed@ImmutableContainer(hc=true), where the text concludes@FinalFields. The cause is the interfaceCounter, which has no implementation in the example: an abstract method of a source interface is computed from its implementations, and with none it comes out@NotModified, where Abstract methods assumes@Modified.Counteris then immutable, and nothing dependent is left. With a mutable class in the place of the interface,Countersis computed@FinalFields, as the text says.SetBasedContainer4in Immutability is computed@FinalFields: rule 2 is decided on the declared type of the public field,Set, and not on the immutable object thatSet.copyOfputs there.The convention that a parameter of function type is
@IgnoreModifications([function-types]) is applied in the annotated APIs only. In source code, theconsumerparameter ofvisitand of the genericforEachis computed@Modified. As a consequenceNonEmptyImmutableList,One,OneWithOneandImmutableOneare not computed@Container, andOneWithOne.visitand the genericforEachare computed@Modified. Written out on a method with a body, the annotation is honoured. Written out on a method without a body in source code, it is not: the parameter is computed@Modified.A method that hands a function on to the
forEachof a field,list.forEach(consumer), leaves the field modified in its hidden content, and the type stops at@FinalFields: rule 1 is decided on the deep verdict, where Accessible and hidden content holds that a type is not responsible for modifications to its hidden content.A modifying call on an
@IgnoreModificationsinstance field leaves the field and the type unmodified, but the method that makes the call is computed@Modified:Catalogue.priceandFieldNode.recordin Ignoring modifications as manual hidden content. For a static field, as inCountAccess, the method is computed@NotModified.Filling an array field with
System.arraycopyin a constructor is computed as a modification of the field, and the type stops at@FinalFields. WithArrays.copyOf, as inArrayContainer3, it does not.ImmutableArrayin Independence of types is computed@FinalFields, and itsiterator()andIteratorImpl@Independent, without the hidden content.C1.useC2in Modification, part 2 is computed@NotModified: the indirect modification through the parameterc2is not found.Stateless lambdas and anonymous classes stop at
@FinalFields, where the example ofApplyLocalFunctions2in Modification, part 2 shows@Immutableand@ImmutableContainer. A known, conservative gap.A class that is neither
finalnorsealedis extensible, and getshc=true. The analyzer does not infer effective finality of a type from the absence of subtypes in the code it sees.An interface’s own immutability verdict is not passed down to its implementations: the abstract methods are read again for each implementation.
The annotated JDK keeps
Iterableat@Container, where More on hidden content shows@ImmutableContainer: anIteratorhasremove, and annotatingIterableas@ImmutableContainer(hc=true)was reverted after a corpus run (2026-09). A source type implementingIterableis judged on its own.For
Lazyin Support classes, the argument that emptyingsupplierat the transition ends the dependence is not computed: the analyzer concludes dependent for the field and for the constructor parameter it is assigned from, whether or notsupplieris emptied. Independence after the mark is computed only where the exposed object is itself eventually immutable. The two@NotNull(content=true)of the listing are not in the shipped source either.
14.4.2. Contracts along the hierarchy
The rule of Inheritance, from @Modified to @NotModified but never back, is enforced against contracts written in source
code and against those of the annotated APIs alike.
A @Modified on a method that overrides one marked @NotModified is reported as contract-conflict; a modifying
implementation or override of a method contracted @NotModified as contract-violation.
Both are reported for the MyString example of Inheritance, and for a modifying equals() or toString() in
any class.
Both are errors against a contract in source code; against a contract of the annotated APIs, the conflict is an error
and the violation a warning.
The violation rests on a computed verdict, and that verdict on the annotated APIs' defaults: a parameter of mutable
type is assumed modified where nobody wrote otherwise, so that a hashCode() returning
Arrays.deepHashCode(properties) comes out modifying.
The @NotModified of Iterable.iterator() and of the list accessors is broken, too, by iterators and lazy lists that change
their own state.
A contract of the annotated APIs is checked, but does not decide: an abstract method in source code that overrides a library method marked
@NotModifiedis still computed from its implementations.An override that modifies where the overridden method is computed, not contracted,
@NotModifiedis a warning (override-weakens-computed): a call through the parent is judged non-modifying.
14.4.3. Ownership
A method whose analysis failed (a degraded method, see Convergence: the iterating analyzer) is assumed to keep all its parameters, and a field that such a method refers to is not owned.
A method that calls itself starts out as not fresh, and stays so unless other evidence decides it.
The fact that flows back into the analysis applies only to a
java.utilcontainer or an array, whose content is exactly its elements.The modification reachability pass (After the fixpoint: the reachability passes) re-derives modification, and must apply the finalizer rule exactly as the iteration does: a finalizer outside the analysed code contributes no modification of its receiver, even though its default without information would read as modifying.
14.4.4. Hidden content
The step back from a modified container to the objects put into it (More on hidden content) is made within one method (CodeLaser/maddi-mod#113), in the mode of the element (CodeLaser/maddi-mod#130). It is not made through a call:
inputinuseAddNewLineis computed@NotModified, where the example shows@Modified. Neither is it made through a field: in the last example of Containers, the parametermessageofErrorLog.addis computed@NotModified, and the type a@Container.A lambda’s modification of its parameter is not propagated through the
visitmethod of an interface in source code:listinaddNewLineis computed@NotModified, where the examples show@Modifiedand@Modified(hc=true).
14.4.5. Structural modification
The structural verdict has been computed since 2026-10 (CodeLaser/maddi-mod#25); its definition by declared types
(The definition, with declared types) dates from CodeLaser/maddi-mod#130.
A run-time check, which validates the analyzer’s verdicts on test suites, applies the definition literally by
walking the heap at the method’s exit.
The analyzer cannot see the heap.
For a modified object that it reached through hidden content, it asks whether that object may also be accessible
content of the owner.
It computes the accessible types of the owner’s declared type: the declared types reachable through accessible
fields, at any depth (Util.accessibleTypes).
The modification is structural when the written object’s type is compatible with one of them, meaning assignable
either way (Util.mayBeAccessibleContent).
Before #130, only the owner’s own fields were compared (CodeLaser/maddi-mod#117).
Since CodeLaser/maddi-mod#159, the type arguments the owner’s types wrote on their fields are accessible types as well
(List<Item> items adds Item), except for the owner itself: a parameter that is a list keeps its elements hidden.
The analyzer makes three approximations, accepted on 2026-11-19. The method names refer to the two examples of Elements of a concrete type.
(a) A modification made by a call is compared by its object and the application objects that object holds, not by
the JDK containers it holds.::
The analyzer knows that a call modifies an object structurally, but not where in that object’s accessible content
the write lands. Taken literally, every application object that the written object holds, and every container it
holds, would be a candidate. With containers included, a List<Node> children in every Node would make every
modification of a list’s elements a modification of the list. Then clearList would lose its read-only
List.
The gap: a call that writes a JDK container that both the element and the owner hold is missed. The run-time check
guards this case.
- (b) The owner’s own type is one of its accessible types only when a field leads back to it.
Stis an accessible type ofStbecause ofparent,Leafone ofLeafbecause ofList<Leaf> children, soclearLeavesis structural.
The gap: an object of the owner’s type held only as hidden content (in a field typedObjector by a type parameter) is missed. The run-time check would see such a write as structural.- (c) The fixpoint engine does not know whether a modification was a direct write or a call.
The reachability pass, on by default, knows the exact write:
e.labeled = truewrites the edge’s ownboolean, so onlyEdgeis compared. The fixpoint engine (setModificationViaReachability(false)) knows only that the edge is modified, so it compares as in (a): sound, but coarser. Until #159,resetshowed the difference; now thatEdgeis an accessible type ofSt, it is structural in both.
For a field of the receiver, the fixpoint engine asks the question with the receiver’s type as the owner, as the reachability pass does: inHolder.touchAll(),for (Item i : touched) i.touch()modifies the receiver structurally and the fieldtouched, a list whose elements changed, deeply only.
The method lift of that example is fernflower’s LabelHelper.liftClosures.
14.4.6. Nullability
The Java output writes the top-level state, and an array’s element state in a type-use flavour; the type arguments reach Java only through maddi 's own
nullableArguments, and the Kotlin and C# types in full.The rounds of Nullability are at most five.
Kotlin smart-casts a
valafter a null test, so a!!is unnecessary where Kotlin itself sees the variable as not null. The analyzer keeps a second set of flow facts restricted to what Kotlin derives (no fact fromrequireNonNull, fromassert, from a Java call’s result, or about avarproperty), and the translation drops the!!exactly there.
14.5. Measurements
Nullability against Guava.
Guava is @NullMarked, with some 16,000 annotated positions in its public and internal API.
The analyzer infers Guava’s nullability with those annotations hidden, and compares per position.
The trivial baselines frame the result: "everything not null" is 2,515 unsafe, "everything nullable" 13,272 noise.
In the first closed-world measurement of 2026-10-07 the inference agreed on 13,306 of the 15,787 top-level
positions, with 354 unsafe and 233 noise; the open-world reading more than halved the unsafe count, to 166, at the
price of leaving a quarter of the positions unspecified.
Later measurements score more positions (type arguments, array elements) against richer JDK contracts, generated
from JSpecify’s annotated JDK, which moves both columns: on 2026-10-13 the closed world stood at 341 unsafe and the
open world at 211.
What remains on the unsafe side is, in the main, Guava’s own API design: public parameters it declares
@Nullable on principle, which no caller in Guava ever passes null to.
Cycle breaking. On the decompiler code base that motivated cycle breaking (Convergence: the iterating analyzer), immutability went from 380 out of 450 types undecided to a single undecided type. On elasticsearch, 51% of 45,000 types remained undecided as long as the breaking pass resolved blocked supertypes only; the cause was fields of external, unannotated types, which the pass now resolves as well.
Ownership. The verdicts have been checked against instrumented test runs, which record every place that holds a claimed owned object, and every holder of a borrowed argument after the call. The contradictions those runs found were holes in the pass, and are fixed.
14.6. Tests that pin the examples
The examples of the first part are analysed by tests in maddi-mod, in the package roadtoimmutability of the
module maddi-modification-analyzer, one class per chapter.
A test states the verdicts that the example shows; where the analyzer computes something else, the test pins what
is computed, with a comment that starts with DEVIATION.
| Test | Examples |
|---|---|
| the examples of Final fields, Modification, Containers and Dependence that are complete classes |
| Immutability, except the illegal |
|
|
|
|
|
|
Older tests, in other packages, pin the remaining examples:
| Test | Examples |
|---|---|
|
|
|
|
|
|
| the rule of Inheritance, with a variant of |
|
|
Not pinned: the examples of Eventual immutability, Nullability and the chapter on other annotations, and the fields of
ApplyLocalFunctions2.
The design notes are in maddi-mod: docs/roadmap/ownership.md, docs/design/eventual-immutability.md and
docs/design/nullability.md.
In practice
15. Support classes
The maddi-support library contains a small selection of support
types: the eventually immutable building blocks that you can use in your project, irrespective
of whether you want analyzer support or not.
The annotations themselves live in a separate library, maddi-annotation, which is the single
dependency maddi-support declares.
We discuss a selection of the building blocks here.
15.1. FlipSwitch
Simpler than FlipSwitch is not possible for an eventually immutable type: it consists solely of a
single boolean, which is at the same time the data and the guard:
io.codelaser.maddi.support.FlipSwitch@ImmutableContainer(after="isSet")
public final class FlipSwitch {
@Final(after="isSet")
private volatile boolean isSet;
@Mark("isSet")
public void set() {
synchronized (this) {
if (isSet) throw new IllegalStateException("Already set");
isSet = true;
}
}
@TestMark("isSet")
@NotModified
public boolean isSet() {
return isSet;
}
@Mark("isSet") (1)
@Modified
public void copy(FlipSwitch other) {
if (other.isSet()) set();
}
}| 1 | The @Mark is present, even if it is executed conditionally. |
The obvious use case for this helper class is to indicate whether a certain job has been done, or not. Once it has been done, it can never be 'undone' again.
15.2. SetOnce
One step up from FlipSwitch is SetOnce: a place-holder for one object which can be filled exactly once:
io.codelaser.maddi.support.SetOnce@ImmutableContainer(hc=true, after="t")
public class SetOnce<T> {
@Final(after="t")
private volatile T t;
@Mark("t")
@Modified
public void set(@NotNull @Independent(hc=true) T t) {
if (t == null) throw new NullPointerException("Null not allowed");
synchronized (this) {
if (this.t != null) {
throw new IllegalStateException("Already set: have " + this.t + ", try to set " + t);
}
this.t = t;
}
}
@Only(after="t")
@NotNull
@Independent(hc=true)
@NotModified
public T get() {
if (t == null) {
throw new IllegalStateException("Not yet set");
}
return t;
}
@TestMark("t")
@NotModified
public boolean isSet() {
return t != null;
}
@Independent (1)
@NotNull
@NotModified
public T getOrDefault(@NotNull T alternative) {
if (isSet()) return get();
return Objects.requireNonNull(alternative);
}
}| 1 | Computed fully @Independent , stronger than the @Independent(hc=true) one would write by hand for a method that may
return the hidden content. |
The analyzer relies heavily on this type.
15.3. EventuallyFinal
Slightly more flexible than SetOnce is EventuallyFinal: the type allows you to keep writing objects using the
setVariable method, until you write using setFinal.
Then, the state changes and the type becomes immutable:
io.codelaser.maddi.support.EventuallyFinal@ImmutableContainer(hc=true, after="isFinal")
public class EventuallyFinal<T> {
private T value;
private boolean isFinal;
@Independent(hc=true)
public T get() {
return value;
}
@Mark("isFinal")
public void setFinal(@Independent(hc=true) T value) {
if (this.isFinal) {
throw new IllegalStateException("Trying to overwrite a final value");
}
this.isFinal = true;
this.value = value;
}
@Only(before="isFinal")
public void setVariable(@Independent(hc=true) T value) {
if (this.isFinal) throw new IllegalStateException("Value is already final");
this.value = value;
}
@TestMark("isFinal")
public boolean isFinal() {
return isFinal;
}
@TestMark(value="isFinal", before=true)
public boolean isVariable() {
return !isFinal;
}
}Note the occurrence of a negated @TestMark annotation: isVariable returns the negation of the normal
isFinal mark test.
15.3.1. EventuallyFinalOnDemand
EventuallyFinalOnDemand is EventuallyFinal with a loader: the before state may carry a Runnable that
produces the final value on first access.
The state transition is the same one, isFinal, with the same four state methods carrying the same annotations,
so nothing in the previous section changes.
Three things are new, and each of them is the only example of its kind in this text.
io.codelaser.maddi.support.EventuallyFinalOnDemand@ImmutableContainer(hc=true, after="isFinal")
public class EventuallyFinalOnDemand<T> {
private volatile T value;
private volatile boolean isFinal;
private volatile Runnable onDemand;
@NotModified(after="isFinal") (1)
public T get() {
if (isFinal) return value;
Runnable runnable = onDemand;
if (runnable != null) {
synchronized (this) {
Runnable again = onDemand; (2)
if (again != null) {
again.run(); (3)
}
}
}
return value;
}
@Mark("isFinal")
public synchronized void setFinal(T value) {
if (this.isFinal) {
throw new IllegalStateException("Trying to overwrite final value");
}
this.value = value;
this.isFinal = true;
this.onDemand = null; (4)
}
@Only(before="isFinal")
public synchronized void setOnDemand(Runnable onDemand) {
assert !isFinal && this.onDemand == null;
this.onDemand = onDemand;
}
}| 1 | @NotModified with an after on a method, rather than on a field as in the table of Eventual immutability.
Before the transition get() may run the loader, which writes; after it, it can only read.
This is a property of its own, and it is what a lazy-loading getter that effects the transition earns. |
| 2 | The loader may have been run, and onDemand cleared, by another thread while this one waited for the monitor. |
| 3 | The monitor is reentrant, which the loader relies on: it calls get() from inside run(), on this thread. |
| 4 | The blanking of Lazy, in a type that the analyzer itself uses.
Only setFinal clears onDemand, and it sets isFinal in the same breath, so no value is ever returned while
a loader is still pending. |
Note what get() does not carry: a @Mark .
The transition happens during the call, but it is effected by the injected Runnable, which calls setFinal —
so the mark is not provable from this type’s own body.
Compare Lazy.get() in Lazy, which marks itself.
EventuallyFinal is what a MethodInfo, ParameterInfo or FieldInfo uses to hold its inspection; TypeInfo
uses this variant, because a type can also arrive by lazy bytecode load, long after the source that mentions it
was parsed.
15.4. Freezable
The previous support class, EventuallyFinal, forms the template for a more general approach to eventual immutability:
allow free modifications, until the type is frozen and no modifications can be allowed anymore.
io.codelaser.maddi.support.Freezable@ImmutableContainer(hc=true, after="frozen") (1)
public abstract class Freezable {
@Final(after="frozen")
private volatile boolean frozen;
@Mark("frozen")
public void freeze() {
ensureNotFrozen();
frozen = true;
}
@TestMark("frozen")
public boolean isFrozen() {
return frozen;
}
@Only(before="frozen")
public void ensureNotFrozen() {
if (frozen) throw new IllegalStateException("Already frozen!");
}
@Only(after="frozen")
public void ensureFrozen() {
if (!frozen) throw new IllegalStateException("Not yet frozen!");
}
}| 1 | The type is abstract, and therefore has hidden content. |
Note that as discussed in Inheritance, it is important for Freezable, as an abstract class, to be immutable:
derived classes can never be immutable when their parents are not immutable.
15.5. SetOnceMap
We discuss one example that makes use of (derives from) Freezable: a freezable map where no objects can be overwritten:
io.codelaser.maddi.support.SetOnceMap@ImmutableContainer(hc=true, after="frozen")
public class SetOnceMap<K, V> extends Freezable {
private final Map<K, V> map = new HashMap<>();
@Only(before="frozen")
public void put(@Independent(hc=true) @NotNull K k,
@Independent(hc=true) @NotNull V v) {
Objects.requireNonNull(k);
Objects.requireNonNull(v);
ensureNotFrozen();
if (isSet(k)) {
throw new IllegalStateException("Already decided on " + k + ": have " +
get(k) + ", want to write " + v);
}
map.put(k, v);
}
@Independent(hc=true)
@NotNull
@NotModified
public V get(K k) {
if (!isSet(k)) throw new IllegalStateException("Not yet decided on " + k);
return Objects.requireNonNull(map.get(k)); (1)
}
public boolean isSet(K k) { (2)
return map.containsKey(k);
}
// ...
}| 1 | The result is @NotNull because of requireNonNull; the nullability pass (Nullability) does not make the connection
between isSet and containsKey. |
| 2 | Implicitly, the parameter K k is @Independent , because the method is @NotModified. |
The code analyzer makes frequent use of this type, often with an additional guard that allows repeatedly putting the same value to a key.
15.6. Lazy
Lazy implements a lazily-initialized immutable field, of unbound generic type T.
Properly implemented, it is an eventually immutable type:
io.codelaser.maddi.support.Lazy@ImmutableContainer(hc=true, after="t")
public class Lazy<T> {
@NotNull(content=true)
@Final(after="t")
private volatile Supplier<T> supplier; // null after the mark
@Final(after="t")
private volatile T t;
public Lazy(@NotNull(content=true) @Independent(hc=true) Supplier<T> supplierParam) { (1)
if (supplierParam == null) throw new NullPointerException("Null not allowed");
this.supplier = supplierParam;
}
@Independent(hc=true)
@NotNull
@Modified
@Mark("t") (2)
public T get() {
T value = t;
if (value != null) return value;
Supplier<T> localSupplier = supplier; (3)
if (localSupplier == null) return t;
t = Objects.requireNonNull(localSupplier.get()); (4)
supplier = null; (5)
return t;
}
@NotModified
@TestMark("t")
public boolean hasBeenEvaluated() {
return t != null;
}
}| 1 | Before the mark the parameter is dependent: the field holds the supplier.
After it only t remains, which is hidden content.
The annotation shows the end state, as the other eventual annotations do (Eventual immutability). |
| 2 | The @Mark annotation is conditional; the transition is triggered by nullity of t |
| 3 | supplier is read once, into a local. Reading the field twice is a race rather than a nicety: two threads
find t null, the first completes and empties supplier, and the second dereferences what it re-reads as null. |
| 4 | Here t, part of the hidden content, becomes content dependent on supplier, as explained in Content dependence.
The statement also causes the @NotNull(content=true) annotation, as defined in Definitions.
It publishes the value before the next line empties the supplier, so a reader that sees supplier == null has
already seen t. |
| 5 | After the transition from mutable to effectively immutable, the field supplier moves out of the picture.
This is what Kotlin’s three Lazy implementations do as well, each with its own initializer = null. |
After calling the marker method get(), t cannot be assigned anymore, and it becomes @Final .
The constructor parameter supplierParam is @Independent(hc=true), as its hidden content (the result of get())
is shared with that of Lazy, namely the field t.
But why is supplier as a field not dependent on the constructor parameter?
Clearly, supplier is part of the accessible content of Lazy: it is held as a Supplier, and its get() method is called.
The criterion is: a modification on one may cause a modification on the other.
Modifications can only be made by calling the get() method, as there are no other methods, and no fields.
Consequently, the field should depend on the constructor parameter, and supplier cannot be @Independent.
Moreover, Lazy.get() calls the supplier’s get(), a modifying method unless contracted otherwise: the field is modified as well.
The answer lies in the eventual nature of Lazy: before the first call to get, the supplier field
is of relevance to the type, and t is not.
After the call to get(), the converse is true, because supplier has been emptied.
A field that holds null has no content.
It cannot be modified, so rule 1 holds for it; and it shares nothing with the argument it was once assigned from, so
rule 3 holds as well.
Because the field is eventually final, it stays null once the transition has taken place.
This is the eventual "blanking out" of modifiable fields in immutable types.
The listing shows the annotations this argument arrives at; Where the analyzer deviates from the definitions has what is computed.
15.7. FirstThen
A variant on SetOnce is FirstThen, an eventually immutable container which starts off with one
value, and transitions to another:
io.codelaser.maddi.support.FirstThen@ImmutableContainer(hc=true, after="first")
public class FirstThen<S, T> {
@Final(after="first")
private volatile S first;
@Final(after="first")
private volatile T then;
private FirstThen(S s, T t) {
this.first = s;
this.then = t;
}
public FirstThen(@NotNull @Independent(hc=true) S first) {
this(Objects.requireNonNull(first), null);
}
public static <S, T> FirstThen<S, T> then(T t) { (1)
return new FirstThen<>(null, Objects.requireNonNull(t));
}
@TestMark(value="first", before=true)
@NotModified
public boolean isFirst() {
return first != null;
}
@TestMark(value="first")
@NotModified
public boolean isSet() {
return first == null;
}
@Mark("first")
public void set(@NotNull @Independent(hc=true) T then) {
Objects.requireNonNull(then);
synchronized (this) {
if (first == null) throw new IllegalStateException("Already set");
this.then = then;
first = null;
}
}
@Only(before="first")
@Independent(hc=true)
@NotModified
@NotNull
public S getFirst() {
if (first == null) throw new IllegalStateException();
return first;
}
@Only(after="first")
@Independent(hc=true)
@NotModified
@NotNull
public T get() {
if (first != null) throw new IllegalStateException("Not yet set"); (2)
assert then != null;
return then;
}
@Override
@NotModified (3)
public boolean equals(@NotNull(absent=true) Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
FirstThen<?, ?> firstThen = (FirstThen<?, ?>) o;
return Objects.equals(first, firstThen.first) &&
Objects.equals(then, firstThen.then);
}
@Override
@NotModified
public int hashCode() {
return Objects.hash(first, then);
}
}| 1 | A factory that starts in the then state: the object is born after its own mark. |
| 2 | The precondition is tested on first, not on then, so that the @Only annotation is recognized; the assert
carries the @NotNull of the result. |
| 3 | equals and hashCode are @NotModified, as java.lang.Object contracts them; the @NotNull(absent=true) on the parameter
records that equals accepts null. |
16. Support classes in the analyzer
Practice what you preach, and all that. The maddi analyzer itself is written in the style this document advocates, and its central data structure is a live example of the two-phase life cycle of Eventual immutability.
The common syntax tree (CST) — the language-agnostic representation shared by the Java and Kotlin
front-ends — is built through the builder pattern throughout: every TypeInfo, MethodInfo and
FieldInfo starts life as a mutable builder during inspection, and is committed into an immutable form
before it is analysed; a type loaded lazily from bytecode during the analysis commits on first use.
After the commit, the object’s structural content — its methods, fields, hierarchy, statements — never
changes again, and the analyzer’s many threads read it freely without synchronization.
The analysis results themselves live in a property map attached to each info object
(element.analysis()), and follow the discipline described in
Convergence: the iterating analyzer: a property value is written once, absence means
"undecided", and the rare legitimate refinements go through a guarded, monotonicity-checking write
facility.
This is eventual immutability at the granularity of a single property: mutable while the fixpoint
iteration runs, frozen from certification onward.
Software engineers using the analyzer as a library can rely on the same guarantee as before: once the
analysis phase is over, all inspected and analyzed information remains stable.
One deliberate exception proves the rule: info objects are single-instance — one TypeInfo per fully
qualified name and source set — and equals is defined on exactly that key, so identity and equality agree
throughout the engine; the immutable-after-commit design is what makes handing these objects across threads
safe in the first place.
17. Other annotations
The maddi project defines a whole host of annotations complementary to the ones required for immutability. We discuss them briefly, and refer to the user manual for an in-depth analysis.
The definitions of this chapter stand on their own; which of them the analyzer computes, and which it only reads as a contract, is listed in What is computed.
17.1. Identity and fluent methods
The analyzer marks methods which return their first parameter with @Identity, and methods which return
this with @Fluent.
The former are convenient to introduce preconditions, the latter occur frequently when chaining methods in builders.
Here is an integrated example:
@Identity and @Fluent@FinalFields @Container(builds=List.class)
class Builder {
@NotNull
@NotModified
@Identity
private static <T> T requireNonNull(@NotNull T t) {
if(t == null) throw new IllegalArgumentException();
return t;
}
private final List<String> list = new ArrayList<>();
@Modified
@Fluent
public Builder add(@NotNull String s) {
list.add(requireNonNull(s));
return this;
}
@Modified
@Fluent
public Builder add(int i) {
list.add(Integer.toString(i));
return this;
}
@NotModified
@ImmutableContainer(hc=true)
public List<String> build() {
return List.copyOf(list);
}
public static final List<String> one23 = new Builder().add(1).add(2).add(3).add("go").build();
}17.2. Utility classes
We use the simple and common definition:
These definitions imply
a utility class has no non-static fields,
it has a single, private, unused constructor,
and its static fields (if it has any) are of immutable type.
17.3. Extension classes
In Java, many classes cannot be extended easily. Implementations of extensions typically use a utility class with the convention that the first parameter of the static method is the object of the extended method call:
@ExtensionClass(of=String[].class)
class ExtendStringArray {
private ExtendStringArray() { throw new UnsupportedOperationException(); }
public static String weave(@NotModified String[] strings) {
// generate a new string by weaving the given strings (concat 1st chars, etc.)
}
public static int appendEach(@Modified String[] strings, String append) {
// append the parameter 'append' to each of the strings in the array
}
}We use the following criteria to designate a class as an extension:
Static classes can be used to 'extend' closed types, as promoted by the Xtend project. Immutable classes can also play the role of extension facilitators, with the additional benefit of having some immutable data to be used as a context.
Note that extension classes will often not be @Container , since the first parameter will be @Modified in many cases.
17.4. Singleton classes
A singleton class is a class which has a mechanism to limit the creation of instances to a maximum of one. The term 'singleton' then refers to this unique instance.
There are two common systems for limiting the number of instances: the creation of an instance in a single static field with a static constructor, and a precondition on a constructor using a private static boolean field.
An example of the first strategy is:
@Singleton
public class SingletonExample {
public static final SingletonExample SINGLETON = new SingletonExample(123);
private final int k;
private SingletonExample(int k) {
this.k = k;
}
public int multiply(int i) {
return k * i;
}
}An example of the second strategy is:
@Singleton
public class SingletonWithPrecondition {
private final int k;
private static boolean created;
public SingletonWithPrecondition(int k) {
if (created) throw new IllegalStateException();
created = true;
this.k = k;
}
public int multiply(int i) {
return k * i;
}
}Appendix A: Annotation overview
When annotating abstract types and methods, or types in the Annotated APIs, observe the following rules.
A method is @Modified unless otherwise specified, its parameters are assumed to be @Modified , unless they are of
immutable type.
Modification is the default; the analyzer must prove non-modification (see Modification).
Due to the large amount of circular type dependencies in the JDK, combined with the current limitations of the analyzer, the implementation of the Annotated API analyzer requires contracted annotations about independence, immutability, and container on the type. The following combinations are possible with respect to independence and immutability:
no independence information: (in)dependence according to the immutability value (not immutable → dependent,
@Immutable(hc=true)→@Independent(hc=true),@Immutable→@Independent)@Independent(absent=true): dependent; this requires that the type is not immutable@Independent(hc=true): this is the default for@Immutable(hc=true),@ImmutableContainer(hc=true), so explicitly writing this annotation is only necessary on non-immutable types@Independent: this is the default for@Immutable,@ImmutableContainer, so explicitly writing this annotation is only useful for mutable or@Immutable(hc=true)types
Recall that abstract types always have hidden content, so the hc=true is always implicitly present on
@Independent and @Immutable , @ImmutableContainer on the type.
We generally do not write hc=false, as that is the default value in the annotation.
An @Immutable annotation on an abstract type is read as hc=true whatever it says.
The analyzer warns when the annotations along a type hierarchy are inconsistent, and when an immutable type has modified members; it does not compare the independence on the type with that on its methods, parameters and fields.
A @Fluent method is assumed to be @Modified , in every type; a method of a type that is at least @Immutable(hc=true) is
@NotModified; otherwise a method without a body takes the modification of the methods it overrides.
Change this by explicitly marking the method @NotModified or @Modified .
Parameters of a non-modifying method are @Independent by default, regardless of an independence annotation on the type.
This can be overwritten by @Independent(absent=true) or @Independent(hc=true) when the method exposes parts of the fields' object graph via its parameters.
Parameters of a modifying method are assumed to be dependent when the type is not immutable, and independent when the type is immutable, the hidden content carrying over from immutable to independent.
Dependence is only explicitly written as @Independent(absent=true) on a type after analysis, when this type has (eventually) final fields and no modifying methods, as a marker to the user to indicate that it is the independence property that is missing to reach immutability.
Marking a non-immutable type with @Independent specifies that no parameter or return value can be dependent.
The hidden content parameter given by the user is ignored: you will still have to mark any method or parameter which communicates hidden content with @Independent(hc=true) .
When a type is immutable, @Independent becomes the default independence annotation for methods and parameters.
You must still use @Independent(hc=true) to indicate communication of hidden content.
Methods marked @Fluent are always @Independent , because returning the type itself does not expose any additional information.
@UnmodifiableView on a bodiless method is a contract that its result is an object nothing is added to or removed from
through that reference (Unmodifiable views): weaker than @Immutable(hc=true) on the result, which a view must not claim,
and unrelated to @Container .
It is never derived from the immutability annotations, and does not feed them.
Following its definition, @UtilityClass on a type implies @Immutable .
A class that is neither final nor sealed is extensible, and therefore carries hidden content; the analyzer does
not infer effective finality from the absence of subtypes in the code it sees.
Parameters of function type ([function-types]) have the @IgnoreModifications annotation, unless explicitly
overwritten by @Modified .
@Fresh on a bodiless method and @Borrowed on a parameter of one are contracts that every implementation must
honour (see Ownership); without them, an abstract method is fresh, and a parameter borrowed, only when all
implementations are.
@Owned is computed, never read as a contract.
None of the three is inherited from the immutability or independence annotations: an immutable object stored in a
field is shared, not owned.
A parameter or return value of reference type that carries no null annotation is unspecified (see
Nullability): it inherits the nullability of the method it overrides, where there is one, and otherwise the
analyzer claims nothing.
Primitives, @Fluent methods and enum constants are @NotNull .
@NotNull(content=true) makes the value and all of its content not null; nullableArguments names, by position, the
type arguments (or, for an array, position 0 for the elements) that may hold null.
A factory method is a static method returning an object of the type of the class.
The return value of a static method that is not a factory is @Independent ; a factory’s return value is judged against its parameters.
A parameter of a factory, or of any modifying method, is @Independent when its type is immutable; otherwise it takes the strongest of the independence contracted on the type, inherited from an overridden method, or implied by the immutability of the parameter type.
Note that utility classes are classes that are deeply immutable and cannot be instantiated, so this applies to their static methods.
In general, annotations are inherited on types, methods and parameters. The properties can deviate,
from
@Modifiedto@NotModifiedis possible, from@NotModifiedto@Modifiedis notindependence can go from left to right in
@Independent(absent=true)→@Independent(hc=true)→@Independent, but not from right to lefta type deriving from an immutable type does not need to be immutable; however, a type deriving from a non-immutable type can never be immutable
When a field is explicitly final (it has the final modifier), @Final is implicit.