javamultithreadingcollections

How to find a thread-safe collection in Java that enforces both uniqueness and size limits on insertion?


I’m looking for a thread-safe collection in Java that:

  1. Enforces uniqueness of elements (like a Set).
  2. Limits the size of the collection (rejects further insertions once the limit is reached).
  3. Does this natively by default (without needing custom logic or wrapping another collection).

So far, I’ve considered:

  1. ConcurrentSkipListSet for uniqueness, but it doesn’t have a size limit.
  2. BlockingQueue for size control, but it doesn’t enforce uniqueness.
  3. Custom implementations using ConcurrentHashMap.newKeySet() for uniqueness and manually managing size.

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?


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)