如何维护不可变类中的可变对象列表

时间:2018-06-12 11:00:31

标签: multithreading concurrency immutability core mutable

我有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方法中执行操作,以便不修改原始对象并且不会创建更多对象。

请帮忙

1 个答案:

答案 0 :(得分:0)

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);