multithreading - 如何维护不可变类中的可变对象列表
问题描述
我有 Immutable 类,其中有 Mutable 类对象的列表。
class Immutable
{
final int id;
final String name;
final List<Mutable> list;
Immutable(int id,String name,List<Mutable> list)
{
this.id=id;
this.name=name;
this.list=list;
}
public List<Mutable> getMutables()
{
List<Mutable> l=new ArrayList<>(this.list);
return l;
}
}
class Mutable
{
String name;
Mutable(String name)
{
this.name=name;
}
}
在这里,我的 getMutables 方法是创建对象并返回克隆的对象。但是如果有这么多线程或请求访问 getMutables 方法,那么它最终会创建多个对象,很快就会出现内存不足的错误。
在 getMutables 方法中做什么,这样原始对象就不会被修改,并且不会创建更多对象。
请帮忙
解决方案
Instead of returning new ArrayList in getMutables(), we can return unmodifibleList of Mutable objects from getMutables().
public List<Mutable> getMutables()
{
return Collections.unmodifiableList(this.list);
}
The unmodifiable Collection method of Collections class is used to return an unmodifiable view of the specified collection. This method allows modules to provide users with “read-only” access to internal collections.
Collections.unmodifiableList(mutableList);
Collections.unmodifiableSet(mutableSet);
Collections.unmodifiableMap(mutableMap);
推荐阅读
- sql - 如何按条件请求列“值喜欢(或包含)特定数组中的字符串(或正则表达式)之一?
- java - 如何随着天数的增加每天获取输出
- caching - 我们应该在微服务中做多少缓存?
- opencensus - 无法使用 opencensus 收集器将跟踪发布到后端
- python - 使用 django-nose 但不使用 Django 的 DiscoverRunner 运行测试时出现重复的关键错误
- ansible - Ansible 多主机传输
- python - 如何在 Python 中导入装饰器包装的函数?
- bash - 无法将环境变量从 makefile 目标传递到 bash 文件
- diff - 多个文件或数据结构上的 diff/delta 术语
- jsf - 如何使用 p:inputText 将转换器传递给复合组件?