Wednesday, March 2, 2016

[Java] Immutable & mutable

Immutable means do not change (read only). Ex : Integer, String, Boolean

Why (advantages)

1 Thread safe ! one object created will always have only one stat for all the threads
2 Reusable : Reduce the creation (CPU, Memeroy) and GC of the same objects.

thus we prefer use String a = "a" but not String a = new String("a") :
when you do new, you create an new object in Heap but not the cont pool.

3 hashCode to be calculated only once

4 As input parameter not need defensive copy(copy the input parameter to avoid change the object), immutable class will make a new one, the original will stay the same.


Disadvantage :  performance(maybe), when an immutable class has to many members, when we want to change on of them, we need to reconstruct the hold object (copy other objects, too) , not preferment.

HOW to create an immutable list? 

  1. don't offer "setters"
  2. should be final : avoid to have sub classes
  3. all members should be private and final: avoid to be changed
  4. if this class has immutable members, these objects cannot be accessible by outer classes, if need to access, need to do defensive copy for it (return an copy of it but not return itself).
How to initialize :    static factory methodbuilder

So for mutable classes:

  1. when use it as a input parameter: should use defensive copy to protect the original data
  2. when you need to share mutable object in multi-threading, you should use lock to make sure the synchronization

 

No comments:

Post a Comment