Immutable Object
An immutable object is an object whose
internal state
remains constant after it has beenentirely created
.
This means that once the object has been assigned to a variable, we can neither update the reference nor mutate the internal state by any means.
This means that the public API of an immutable object guarantees us that it will behave in the same way during its wholelifetime
.
java 中反射可以突破这个限制,正常情况下,考虑 public API.
String Immutable in Java 好处
string intern pool
heap memory 中一个特殊的内存块。
专门存放如 String str = “abc”
,这种字面量字符串的地方。
caching
hash code caching。
String 类型非常常见。被 String.hashCode() 用来 bucketing,散列值作为 index。一旦是可变的,会造成不好的效果。
security
一般用户名等信息是 String,其实所有的信息都可以看成字符串。
假定 String 是可变的,要对 String name = “XXX” 做安全校验, caller 调用另一个对象的方法把 name 传过去,已经通过校验,因为是可变的,caller 又修改了这个 name 的值,相当于绕过了这个安全校验。
synchronization
不可变
的东西,天然就是线程安全的。如果要改变,会生成一个新的 String,旧的依然保持不变。
performance
String str = “abc” 这种是 compile-time
就已经决定的了。整个字符串常量池只会保存一份 "abc"
这就节省了内存。
不像 String str = new String("abc")
这种是 runtime 才知道的。