What are immutable objects?

 ̄綄美尐妖づ 提交于 2019-12-23 09:04:21

问题


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


回答1:


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.




回答2:


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.




回答3:


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.



来源:https://stackoverflow.com/questions/2095630/what-are-immutable-objects

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!