How to return a thread safe/immutable Collection in Java?

zw324 picture zw324 · Jul 12, 2011 · Viewed 12.3k times · Source

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

would do the trick.

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

Thanks for any inputs!

Answer

Ray picture Ray · Jul 12, 2011

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 in particular is the implementation you're looking for. Here is a quick sketch of some of the features of Guava's ImmutableCollections.