什么是不可变对象?
线程安全和不可变对象有什么关系?在多个线程之间共享单个资源是否更容易?如果不可变对象是无状态的,那么它们可以被集中在像 J2EE 容器这样的容器中吗?
谢谢
What is the relationship with thread-safety and immutable objects? Does it makes easier to share a single resource among multiple threads? If immutable objects are stateless, can they be pooled in a container like a J2EE container?
thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
不可变对象是不能更改的对象。如果一个对象不能被改变,那么就不用担心竞争线程会在执行线程“背后”改变对象状态,因此不可变对象不需要通过同步或其他技术来保护。
Immutable objects are objects that can not be changed. If an object can not be changed, then there is no concern that a competing thread will change the object state "behind the back" of the executing thread, and therefore immutable objects do not need to be protected via synchronization or some other technique.
线程安全对象是允许多个线程同时访问的对象。它们的实现保证(例如通过锁定/同步方法/...)它们不会进入无效状态。此外,不应有数据丢失。
不可变对象在创建后不得更改。所以:是的,他们是某种无国籍的人。
由于不可变对象无法更改,因此不需要锁定 - 对对象的读取访问始终是线程安全的(当不修改变量时)。因此,真正的不可变对象总是线程安全的。
Threadsafe objects are objects which allow to be accessed concurrently by multiple threads. Their implementation guarantees (for example by lockings / synchronzized methods / ...) that they will not get into a invalid state. In addition, there should be no loss of data.
Immutable objects may not be altered after their creation. So: Yes, they are some kind of stateless.
As immutable objects can not be changed, there is no need for locking - reading access to objects is always threadsafe (when not modifying variables). Therefore, real immutable objects are always threadsafe.
不可变对象:不改变其内部状态的对象。
与线程安全的关系:如果一个对象不能被改变,那么跨线程使用它是安全的,即不需要锁或类似的东西来确保跨线程的一致性。
Immutable Object: An object that doesn't change its internal state.
The relationship with thread-safety: if an object cannot be mutated, it is safe to use it across threads i.e. no need to have locks or the like to ensure consistency across threads.