Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Different between immutable and effectively immutable objects?

Tags:

This is a sentence from Java Concurrency in Practice

Shared read-only objects include immutable and effectively immutable objects.

What are the differences between immutable and effectively immutable objects?

like image 792
sheidaei Avatar asked May 21 '13 19:05

sheidaei


People also ask

What is the difference between immutable object and mutable object?

Objects whose value can change are said to be mutable; objects whose value is unchangeable once they are created are called immutable.

What is difference between mutable and immutable files?

Mutable is a fancy way of saying that the internal state of the object is changed/mutated. So, the simplest definition is: An object whose internal state can be changed is mutable. On the other hand, immutable doesn't allow any change in the object once it has been created.

What is the meaning of immutable objects?

In object-oriented and functional programming, an immutable object (unchangeable object) is an object whose state cannot be modified after it is created. This is in contrast to a mutable object (changeable object), which can be modified after it is created.

What is mutable and immutable object give example?

The mutable class examples are StringBuffer, Java. util. Date, StringBuilder, etc. Whereas the immutable objects are legacy classes, wrapper classes, String class, etc.


1 Answers

Instances of a class that is not extensible and whose fields are all final and themselves immutable are immutable.

Instances of a class whose fields cannot be mutated because of details of its methods are effectively immutable. For example:

final class C {
  final boolean canChange;
  private int x;
  C(boolean canChange) { this.canChange = canChange; }
  public void setX(int newX) {
    if (canChange) {
      this.x = newX;
    } else {
      throw new IllegalStateException();
    }
  }
}

Some instances of C are effectively immutable and some are not.

Another example is zero-length arrays. They are effectively immutable even though their containing class is not provably immutable since there is no element of them which can be changed.


Joe-E uses a verifier to prove that some classes only allow for immutable instances. Anything marked with the Immutable marker interface are checked and certain classes like String (effectively immutable since its char[] does not escape) are grandfathered in as immutable.

Joe-E: A Security-Oriented Subset of Java says

The Immutable interface, defined by the Joe-E library, is treated specially by the language: the Joe-E verifier checks that every object implementing this interface will be (deeply) immutable, and raises a compile-time error if this cannot be automatically verified.

like image 166
Mike Samuel Avatar answered Oct 12 '22 00:10

Mike Samuel