Friday, 22 April 2016

What are immutable objects and are they thread-safe ?


Immutable object is one whose state cannot be changed after construction.

In an immutable object : 
  • State cannot be modified after construction
  • All fields are final
  • this reference is not escape in the construction
Example

// Final class and state, so not modifiable
public final class Test {
  private final Set<String> cities = new HashSet<String>();

  // In constructor, No this reference is escaped
  public Test() {
    cities.add("Delhi");
    cities.add("Mumbai");
    cities.add("Chennai");
  }

  public boolean isExists(String city) {
    return cities.contains(city);
  }
}


Immutable objects are always thread-safe.
They can be used safely by any thread without additional synchronization.

They can be published through any mechanism (No need to worry while sharing them)


Mutable objects
Mutable objects must be safely published, and must be either thread-safe or guarded by a lock.

No comments:

Post a Comment

Note: only a member of this blog may post a comment.