如何在Java中返回线程安全/不变集合? [英] How to return a thread safe/immutable Collection in Java?

查看:115
本文介绍了如何在Java中返回线程安全/不变集合?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我正在编码的项目中,我需要从函数返回线程安全且不变的视图.但是,我不确定.由于synchronizedListunmodifiableList仅返回列表的视图,因此我不知道

In the project I am coding, I need to return a thread safe and immutable view from a function. However, I am unsure of this. Since synchronizedList and unmodifiableList just return views of a list, I don't know if

Collections.synchronizedList(Collections.unmodifiableList(this.data));

可以解决问题.

任何人都可以告诉我这是否正确,如果不正确,是否有任何情况可能会失败?

Could anyone tell me if this is correct, and in case it is not, are there any situations that this would likely to fail?

感谢您的投入!

推荐答案

我发现这是JDK中的真正空白.幸运的是,由Java Collections设计师 Joshua Bloch 领导的Google团队创建了

I find this to be a real gap in the JDK. Fortunately, a team over a Google, led by Java Collections designer Joshua Bloch, have created a library that includes truly immutable collections.

ImmutableList 特别是您的实现正在寻找. 此处是番石榴ImmutableCollections某些功能的简要概述.

ImmutableList in particular is the implementation you're looking for. Here is a quick sketch of some of the features of Guava's ImmutableCollections.

这篇关于如何在Java中返回线程安全/不变集合?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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