blackdrag commented on code in PR #3259:
URL: https://github.com/apache/groovy/pull/3259#discussion_r4545640842


##########
subprojects/groovy-ginq/src/main/groovy/org/apache/groovy/ginq/provider/collection/runtime/QueryableCollection.java:
##########
@@ -684,12 +690,128 @@ public long size() {
     }
 
     /**
-     * Returns a reusable stream over the current elements.
+     * Returns a new stream over the current elements. Creating the stream 
does not
+     * pull. An iterable source is read again by every stream. A one-shot 
stream is
+     * pulled into a buffer as it is consumed, and a later call replays that 
buffer
+     * instead of returning the stream that was already handed out.
      *
-     * @return the element stream
+     * @return a stream that has not been consumed
      */
     @Override
     public Stream<T> stream() {
+        writeLock.lock();
+        try {
+            if (sourceIterable != null) {
+                Stream<T> fresh = toStream(sourceIterable);
+                if (!fresh.isParallel() && isParallel()) {
+                    fresh = fresh.parallel();
+                }
+                return fresh;
+            }
+            bindUpstream();
+            return StreamSupport.stream(ReplaySpliterator::new, 
upstreamCharacteristics, false);
+        } finally {
+            writeLock.unlock();
+        }
+    }
+
+    /**
+     * Binds the one-shot source. The size is recorded before any element is 
pulled,
+     * so a later {@code count} can use it without running projections.
+     */
+    private void bindUpstream() {
+        if (upstreamBound) {
+            return;
+        }
+        upstreamBound = true;
+        upstream = openStream().spliterator();
+        long exact = upstream.getExactSizeIfKnown();
+        upstreamExactSize = exact;
+        upstreamCharacteristics = Spliterator.ORDERED;
+        if (exact >= 0) {
+            upstreamCharacteristics |= Spliterator.SIZED | 
Spliterator.SUBSIZED;
+        }
+    }
+
+    /**
+     * One cursor over a one-shot source. Elements are appended to {@link 
#replay}
+     * as they are pulled, so another stream can read them from the start.
+     * A sized source reports that size, and {@code Stream.count} then does 
not pull.
+     */
+    private final class ReplaySpliterator implements Spliterator<T> {
+        private int cursor;
+
+        @Override
+        public boolean tryAdvance(Consumer<? super T> action) {
+            writeLock.lock();

Review Comment:
   that will potentially mean a lot of lock calls



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]

Reply via email to