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

Viewed 12453

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!

6 Answers

copyOf

Yes, now built into Java 10 and later.

Each of these returns a separate collection of the objects found in the original. The returned collection is not a view onto the original, as is the case with the Collections.unmodifiable… utility class methods.

The copyOf methods are copying the references (pointers), not the objects. So, not much memory is involved.

Java 9+ ImmutableCollections are thread safe. For example, List.of, Map.of, Map.copyOf(Java 10+)... According to oracle doc,

One advantage of an immutable collection is that it is automatically thread safe. After you create a collection, you can hand it to multiple threads, and they will all see a consistent view.

Read more at: oracle docs

Related