java-String 为什么设计成不可变?

本文探讨了Java中String的不可变特性如何通过反射保持不变,以及其带来的好处,如内存效率、安全性、线程同步和性能提升。重点讲解了字符串常量池、缓存和安全校验等内容。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Immutable Object

An immutable object is an object whose internal state remains constant after it has been entirely 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 whole lifetime.
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 才知道的。

Reference

  1. https://www.baeldung.com/java-immutable-object
  2. https://www.baeldung.com/java-string-immutable
  3. https://www.artima.com/articles/james-gosling-on-java-may-2001#part13
  4. https://www.baeldung.com/java-string-pool
  5. https://stackoverflow.com/questions/20945049/is-a-java-string-really-immutable
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值