Immutable Class
Immutable?
- The most common case is String:
- Why String is immutable in Java?
- String pool is possible only because String is immutable in java, this way Java Runtimes saves a lot of java heap space.
- If String is mutable then it would cause severe security threat to the application. (For example, database username, password are passed as String to get database connection and in socket programming host and port details passed as String. Since String is immutable it’s value can’t be changed otherwise any hacker could change the referenced value to cause security issues in the application.)
- immuatble --> safe for multithreading. (a single String can be shared across different threads. This avoid the usage of synchronization). Immutable is implicitly thread safe.
- its hashcode is cached at the time of creation.
- Why String is immutable in Java?
Use case
- Immutable class is good for caching purpose. Inherently thread-safe.
How to create an immutable class
- Declare the class as final so it can't be extended.
- Make all fields private so that direct access is not allowed.
- No setter methods for vaiables.
- Make all mutable fields final so that it's value can be assigned only once.
- Initialize all the fileds via a constructor performing deep copy.
public FinalClassExample(int i, String n, HashMap<String,String> hm){ System.out.println("Performing Deep Copy for Object initialization"); this.id=i; this.name=n; HashMap<String,String> tempMap=new HashMap<String,String>(); String key; Iterator<String> it = hm.keySet().iterator(); while(it.hasNext()){ key=it.next(); tempMap.put(key, hm.get(key)); } this.testMap=tempMap; } - Perform cloning of objects in the getter methods to return a copy rather than returning the actual object reference.
/** * Accessor function for mutable objects */ public HashMap<String, String> getTestMap() { //return testMap; return (HashMap<String, String>) testMap.clone(); }
满地都是六便士,她却抬头看见了月亮。
浙公网安备 33010602011771号