Java Concurrency - Immutable Object

Java Conceptuel Diagram

About

Immutable object in Java Concurrency.

Rules

  • Don't provide “setter” methods — methods that modify fields or objects referred to by fields.
  • Make all fields final and private.
  • Don't allow subclasses to override methods. The simplest way to do this is to declare the class as final. A more sophisticated approach is to make the constructor private and construct instances in factory methods.
  • If the instance fields include references to mutable objects, don't allow those objects to be changed:
    • Don't provide methods that modify the mutable objects.
    • Don't share references to the mutable objects. Never store references to external, mutable objects passed to the constructor; if necessary, create copies, and store references to the copies. Similarly, create copies of your internal mutable objects when necessary to avoid returning the originals in your methods.

Library

  • com.google.common.collect (Guava)
List<Table> allTables = ImmutableList.copyOf(Table.values());
final String value1;
final Boolean blue;

private Session(String value1, boolean isBlue)
{
   this.value1 = value1;
   this.isBlue = isBlue;
}

public Session withBlue(boolean isBlue)
{
  return new Session(
          this.value1,
          this.isBlue
  );
}

Collections

since Java10, Create new collection instances from existing instances

  • List.copyOf,
  • Set.copyOf,
  • and Map.copyOf .

Stream

Java - Stream Processing New methods toUnmodifiableList, toUnmodifiableSet, and toUnmodifiableMap have been added to the Collectors class in the Stream package.

Documentation / Reference

See Java Tuto - Immutable





Discover More
Java Collection Type
Java - (Collection|container) Framework (Types)

A collection (known also as a container) is an object that groups multiple objects (elements) into a single unit. Collections are used to store, retrieve, manipulate, and communicate aggregate data. ...
Java Conceptuel Diagram
Java - Integer

integer data type in Java. int (or Integer) is the 32 bit implementation of an integer. Java can also store an integer on 64 bit with a long. An integer in java is a sub-class of number They are...



Share this page:
Follow us:
Task Runner