什么是不可变的对象? [英] What are immutable objects?

查看:77
本文介绍了什么是不可变的对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

与线程安全和不可变对象有什么关系?在多个线程之间共享单个资源是否更容易?如果不可变对象是无状态的,可以将它们合并到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?

谢谢

推荐答案

线程安全对象是允许多个线程同时访问的对象.它们的实现保证了(例如通过锁定/同步方法/...)它们不会进入无效状态.另外,应该不会丢失任何数据.

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.

这篇关于什么是不可变的对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆