Class CyclicThreadSafeCollection<E>

  • All Implemented Interfaces:
    Iterable<E>, Collection<E>

    @ThreadSafe
    public class CyclicThreadSafeCollection<E>
    extends Object
    implements Collection<E>
    Circular thread-safe Collection.

    At most capacity elements are preserved and when more added, oldest elements are deleted. Collection preserves insertion order of the elements so the oldest is the first one.

    The class does not implement selective deletion operations (remove(), removeAll(), retainAll()) but it implements clear().

    All operations, including iteration, are thread safe. Operations add(), size() and isEmpty() performs in constant time. The rest of the operations have linear time complexity, while never holding the lock to perform any custom logic (such as calling contains() on elements) or entering synchronized section on any other monitor except for the internal lock. In such cases, lock is used only to make the copy of the content.

    Author:
    ogondza.
    • Constructor Detail

      • CyclicThreadSafeCollection

        public CyclicThreadSafeCollection​(int capacity)
    • Method Detail

      • add

        public boolean add​(E e)
        Specified by:
        add in interface Collection<E>
      • addAll

        public boolean addAll​(@NonNull
                              Collection<? extends E> c)
        Add several elements at once.

        It is not guaranteed the elements will be consecutive in the collection (other thread can add elements in between) but it is guaranteed to preserve order.

        Specified by:
        addAll in interface Collection<E>
      • iterator

        @NonNull
        public Iterator<E> iterator()
        Create thread-safe iterator for collection snapshot.

        Iterated elements represent a snapshot of the collection.

        Specified by:
        iterator in interface Collection<E>
        Specified by:
        iterator in interface Iterable<E>
      • size

        @Nonnegative
        public int size()
        Number of contained elements, never more than capacity.
        Specified by:
        size in interface Collection<E>
      • capacity

        @Nonnegative
        public int capacity()
        Maximal collection capacity.
      • toList

        @NonNull
        public List<E> toList()
        Get elements in separate collection.
      • toArray

        @NonNull
        public <T> T[] toArray​(@NonNull
                               T[] ret)
        Specified by:
        toArray in interface Collection<E>