I’m looking for a thread-safe collection in Java that:
So far, I’ve considered:
ConcurrentSkipListSet
for uniqueness, but it doesn’t have a size limit.BlockingQueue
for size control, but it doesn’t enforce uniqueness.Is there a standard Java thread-safe collection that provides both features (uniqueness and size limitation) without needing custom handling? Or do I need to implement my own solution?
You can try this (tried using Java SE 17):
Integer [] ints = { 1, 2, 3 }; // substitute your own objects
Set<Integer> set1 = Set.of(ints);
System.out.println("set: " + set1);
set1.add(4); // throws java.lang.UnsupportedOperationException
Set<Integer> set2 = Collections.synchronizedSet(set1);
System.out.println("set2: " + set2);
set2.add(4); // throws java.lang.UnsupportedOperationException
Reference: static Set of(E... elements)