Class LockIterator<T>

  • Type Parameters:
    T - The element type for this iterator
    All Implemented Interfaces:
    java.lang.AutoCloseable, java.util.Iterator<T>, ClosableIterator<T>

    public class LockIterator<T>
    extends java.lang.Object
    implements ClosableIterator<T>
    Simple implementation of a ClosableIterator that uses a lock.
    Close is an idempotent function and can be performed multiple times without effects beyond first invocation.
    This is deployed by CacheView.lockedIterator() to allow read-only access to the underlying structure without the need to clone it, unlike the normal iterator.

    This closes automatically when hasNext() returns false but its recommended to only be used within a try-with-resources block for safety.

    Example

    This can handle any exceptions thrown while iterating and ensures the lock is released correctly.
    
     try (ClosableIterator<T> it = cacheView.lockedIterator()) {
         while (it.hasNext()) {
             consume(it.next());
         }
     }
     
    Since:
    4.0.0
    • Constructor Summary

      Constructors 
      Constructor Description
      LockIterator​(java.util.Iterator<? extends T> it, java.util.concurrent.locks.Lock lock)  
    • Method Summary

      All Methods Instance Methods Concrete Methods 
      Modifier and Type Method Description
      void close()  
      boolean hasNext()  
      T next()  
      • Methods inherited from class java.lang.Object

        equals, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
      • Methods inherited from interface java.util.Iterator

        forEachRemaining, remove
    • Constructor Detail

      • LockIterator

        public LockIterator​(@Nonnull
                            java.util.Iterator<? extends T> it,
                            java.util.concurrent.locks.Lock lock)
    • Method Detail

      • close

        public void close()
        Specified by:
        close in interface java.lang.AutoCloseable
        Specified by:
        close in interface ClosableIterator<T>
      • hasNext

        public boolean hasNext()
        Specified by:
        hasNext in interface java.util.Iterator<T>
      • next

        @Nonnull
        public T next()
        Specified by:
        next in interface java.util.Iterator<T>