All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.landawn.abacus.util.stream.ParallelIteratorStream Maven / Gradle / Ivy

There is a newer version: 1.10.1
Show newest version
/*
 * Copyright (C) 2016 HaiYang Li
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
 * in compliance with the License. You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software distributed under the License
 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
 * or implied. See the License for the specific language governing permissions and limitations under
 * the License.
 */

package com.landawn.abacus.util.stream;

import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Comparator;
import java.util.Deque;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.Set;
import java.util.concurrent.Callable;
import java.util.concurrent.atomic.AtomicLong;

import com.landawn.abacus.util.ByteIterator;
import com.landawn.abacus.util.CharIterator;
import com.landawn.abacus.util.CompletableFuture;
import com.landawn.abacus.util.DoubleIterator;
import com.landawn.abacus.util.FloatIterator;
import com.landawn.abacus.util.Holder;
import com.landawn.abacus.util.Indexed;
import com.landawn.abacus.util.IntIterator;
import com.landawn.abacus.util.LongIterator;
import com.landawn.abacus.util.LongMultiset;
import com.landawn.abacus.util.Multimap;
import com.landawn.abacus.util.Multiset;
import com.landawn.abacus.util.MutableBoolean;
import com.landawn.abacus.util.MutableLong;
import com.landawn.abacus.util.N;
import com.landawn.abacus.util.Nth;
import com.landawn.abacus.util.NullabLe;
import com.landawn.abacus.util.Pair;
import com.landawn.abacus.util.ShortIterator;
import com.landawn.abacus.util.Try;
import com.landawn.abacus.util.function.BiConsumer;
import com.landawn.abacus.util.function.BiFunction;
import com.landawn.abacus.util.function.BiPredicate;
import com.landawn.abacus.util.function.BinaryOperator;
import com.landawn.abacus.util.function.Consumer;
import com.landawn.abacus.util.function.Function;
import com.landawn.abacus.util.function.IntFunction;
import com.landawn.abacus.util.function.Predicate;
import com.landawn.abacus.util.function.Supplier;
import com.landawn.abacus.util.function.ToByteFunction;
import com.landawn.abacus.util.function.ToCharFunction;
import com.landawn.abacus.util.function.ToDoubleFunction;
import com.landawn.abacus.util.function.ToFloatFunction;
import com.landawn.abacus.util.function.ToIntFunction;
import com.landawn.abacus.util.function.ToLongFunction;
import com.landawn.abacus.util.function.ToShortFunction;
import com.landawn.abacus.util.function.TriConsumer;
import com.landawn.abacus.util.function.TriFunction;
import com.landawn.abacus.util.stream.ExIterator.QueuedIterator;

/**
 * This class is a sequential, stateful and immutable stream implementation.
 *
 * @param 
 * @since 0.8
 * 
 * @author Haiyang Li
 */
final class ParallelIteratorStream extends IteratorStream {
    private final int maxThreadNum;
    private final Splitor splitor;
    private volatile IteratorStream sequential;

    ParallelIteratorStream(final Iterator values, final Collection closeHandlers, final boolean sorted,
            final Comparator comparator, final int maxThreadNum, final Splitor splitor) {
        super(values, closeHandlers, sorted, comparator);

        this.maxThreadNum = N.min(maxThreadNum, MAX_THREAD_NUM_PER_OPERATION);
        this.splitor = splitor == null ? DEFAULT_SPLITOR : splitor;
    }

    ParallelIteratorStream(final Stream stream, final Set closeHandlers, final boolean sorted, final Comparator comparator,
            final int maxThreadNum, final Splitor splitor) {
        this(stream.iterator(), mergeCloseHandlers(stream, closeHandlers), sorted, comparator, maxThreadNum, splitor);
    }

    @Override
    public Stream filter(final Predicate predicate) {
        if (maxThreadNum <= 1) {
            return new ParallelIteratorStream<>(sequential().filter(predicate).iterator(), closeHandlers, sorted, cmp, maxThreadNum, splitor);
        }

        final List> iters = new ArrayList<>(maxThreadNum);

        for (int i = 0; i < maxThreadNum; i++) {
            iters.add(new ExIterator() {
                private T next = null;
                private boolean hasNext = false;

                @Override
                public boolean hasNext() {
                    if (hasNext == false) {
                        while (true) {
                            synchronized (elements) {
                                if (elements.hasNext()) {
                                    next = elements.next();
                                } else {
                                    break;
                                }
                            }

                            if (predicate.test(next)) {
                                hasNext = true;
                                break;
                            }
                        }
                    }

                    return hasNext;
                }

                @Override
                public T next() {
                    if (hasNext == false && hasNext() == false) {
                        throw new NoSuchElementException();
                    }

                    hasNext = false;
                    return next;
                }
            });
        }

        return new ParallelIteratorStream<>(Stream.parallelConcat(iters, asyncExecutor), closeHandlers, false, null, maxThreadNum, splitor);
    }

    @Override
    public Stream takeWhile(final Predicate predicate) {
        if (maxThreadNum <= 1) {
            return new ParallelIteratorStream<>(sequential().takeWhile(predicate).iterator(), closeHandlers, sorted, cmp, maxThreadNum, splitor);
        }

        final List> iters = new ArrayList<>(maxThreadNum);
        final MutableBoolean hasMore = MutableBoolean.of(true);

        for (int i = 0; i < maxThreadNum; i++) {
            iters.add(new ExIterator() {
                private T next = null;
                private boolean hasNext = false;

                @Override
                public boolean hasNext() {
                    if (hasNext == false && hasMore.isTrue()) {
                        synchronized (elements) {
                            if (elements.hasNext()) {
                                next = elements.next();
                                hasNext = true;
                            } else {
                                hasMore.setFalse();
                            }
                        }

                        if (hasNext && predicate.test(next) == false) {
                            hasNext = false;
                            hasMore.setFalse();
                        }
                    }

                    return hasNext;
                }

                @Override
                public T next() {
                    if (hasNext == false && hasNext() == false) {
                        throw new NoSuchElementException();
                    }

                    hasNext = false;
                    return next;
                }
            });
        }

        return new ParallelIteratorStream<>(Stream.parallelConcat(iters, asyncExecutor), closeHandlers, false, null, maxThreadNum, splitor);
    }

    @Override
    public Stream dropWhile(final Predicate predicate) {
        if (maxThreadNum <= 1) {
            return new ParallelIteratorStream<>(sequential().dropWhile(predicate).iterator(), closeHandlers, sorted, cmp, maxThreadNum, splitor);
        }

        final List> iters = new ArrayList<>(maxThreadNum);
        final MutableBoolean dropped = MutableBoolean.of(false);

        for (int i = 0; i < maxThreadNum; i++) {
            iters.add(new ExIterator() {
                private T next = null;
                private boolean hasNext = false;

                @Override
                public boolean hasNext() {
                    if (hasNext == false) {
                        // Only one thread is kept for running after it's dropped.
                        if (dropped.isTrue()) {
                            synchronized (elements) {
                                if (elements.hasNext()) {
                                    next = elements.next();
                                    hasNext = true;
                                }
                            }
                        } else {
                            while (dropped.isFalse()) {
                                synchronized (elements) {
                                    if (elements.hasNext()) {
                                        next = elements.next();
                                    } else {
                                        break;
                                    }
                                }

                                if (predicate.test(next) == false) {
                                    hasNext = true;
                                    dropped.setTrue();
                                    break;
                                }
                            }

                            if (hasNext == false && dropped.isTrue()) {
                                synchronized (elements) {
                                    if (elements.hasNext()) {
                                        next = elements.next();
                                        hasNext = true;
                                    }
                                }
                            }
                        }
                    }

                    return hasNext;
                }

                @Override
                public T next() {
                    if (hasNext == false && hasNext() == false) {
                        throw new NoSuchElementException();
                    }

                    hasNext = false;
                    return next;
                }
            });
        }

        return new ParallelIteratorStream<>(Stream.parallelConcat(iters, asyncExecutor), closeHandlers, false, null, maxThreadNum, splitor);
    }

    @Override
    public  Stream map(final Function mapper) {
        if (maxThreadNum <= 1) {
            return new ParallelIteratorStream<>(sequential().map(mapper).iterator(), closeHandlers, false, null, maxThreadNum, splitor);
        }

        final List> iters = new ArrayList<>(maxThreadNum);

        for (int i = 0; i < maxThreadNum; i++) {
            iters.add(new ExIterator() {
                private Object next = NONE;

                @Override
                public boolean hasNext() {
                    if (next == NONE) {
                        synchronized (elements) {
                            if (elements.hasNext()) {
                                next = elements.next();
                            }
                        }
                    }

                    return next != NONE;
                }

                @Override
                public R next() {
                    if (next == NONE && hasNext() == false) {
                        throw new NoSuchElementException();
                    }

                    R result = mapper.apply((T) next);
                    next = NONE;
                    return result;
                }
            });
        }

        return new ParallelIteratorStream<>(Stream.parallelConcat(iters, asyncExecutor), closeHandlers, false, null, maxThreadNum, splitor);
    }

    @Override
    public  Stream biMap(final BiFunction mapper, final boolean ignoreNotPaired) {
        if (maxThreadNum <= 1) {
            return new ParallelIteratorStream<>(sequential().biMap(mapper, ignoreNotPaired).iterator(), closeHandlers, false, null, maxThreadNum, splitor);
        }

        final List> iters = new ArrayList<>(maxThreadNum);

        for (int i = 0; i < maxThreadNum; i++) {
            iters.add(new ExIterator() {
                private Object pre = NONE;
                private Object next = NONE;

                @Override
                public boolean hasNext() {
                    if (pre == NONE) {
                        synchronized (elements) {
                            if (elements.hasNext()) {
                                pre = elements.next();

                                if (elements.hasNext()) {
                                    next = elements.next();
                                }
                            }
                        }
                    }

                    return ignoreNotPaired ? next != NONE : pre != NONE;
                }

                @Override
                public R next() {
                    if (next == NONE && hasNext() == false) {
                        throw new NoSuchElementException();
                    }

                    final R result = mapper.apply((T) pre, next == NONE ? null : (T) next);
                    pre = NONE;
                    next = NONE;
                    return result;
                }
            });
        }

        return new ParallelIteratorStream<>(Stream.parallelConcat(iters, asyncExecutor), closeHandlers, false, null, maxThreadNum, splitor);
    }

    @Override
    public  Stream triMap(final TriFunction mapper, final boolean ignoreNotPaired) {
        if (maxThreadNum <= 1) {
            return new ParallelIteratorStream<>(sequential().triMap(mapper, ignoreNotPaired).iterator(), closeHandlers, false, null, maxThreadNum, splitor);
        }

        final List> iters = new ArrayList<>(maxThreadNum);

        for (int i = 0; i < maxThreadNum; i++) {
            iters.add(new ExIterator() {
                private Object prepre = NONE;
                private Object pre = NONE;
                private Object next = NONE;

                @Override
                public boolean hasNext() {
                    if (prepre == NONE) {
                        synchronized (elements) {
                            if (elements.hasNext()) {
                                prepre = elements.next();

                                if (elements.hasNext()) {
                                    pre = elements.next();

                                    if (elements.hasNext()) {
                                        next = elements.next();
                                    }
                                }
                            }
                        }
                    }

                    return ignoreNotPaired ? next != NONE : prepre != NONE;
                }

                @Override
                public R next() {
                    if (next == NONE && hasNext() == false) {
                        throw new NoSuchElementException();
                    }

                    final R result = mapper.apply((T) prepre, pre == NONE ? null : (T) pre, next == NONE ? null : (T) next);
                    prepre = NONE;
                    pre = NONE;
                    next = NONE;
                    return result;
                }
            });
        }

        return new ParallelIteratorStream<>(Stream.parallelConcat(iters, asyncExecutor), closeHandlers, false, null, maxThreadNum, splitor);
    }

    @Override
    public Stream mapFirst(final Function mapperForFirst) {
        N.requireNonNull(mapperForFirst);

        if (maxThreadNum <= 1) {
            return new ParallelIteratorStream<>(sequential().mapFirst(mapperForFirst).iterator(), closeHandlers, false, null, maxThreadNum, splitor);
        }

        if (elements.hasNext()) {
            T first = elements.next();
            return prepend(Stream.of(first).map(mapperForFirst));
        } else {
            return this;
        }
    }

    @Override
    public  Stream mapFirstOrElse(final Function mapperForFirst, final Function mapperForElse) {
        N.requireNonNull(mapperForFirst);
        N.requireNonNull(mapperForElse);

        if (maxThreadNum <= 1) {
            return new ParallelIteratorStream<>(sequential().mapFirstOrElse(mapperForFirst, mapperForElse).iterator(), closeHandlers, false, null, maxThreadNum,
                    splitor);
        }

        if (elements.hasNext()) {
            final Function mapperForFirst2 = (Function) mapperForFirst;
            final Function mapperForElse2 = (Function) mapperForElse;
            final T first = elements.next();

            return map(mapperForElse2).prepend(Stream.of(first).map(mapperForFirst2));
        } else {
            return (Stream) this;
        }
    }

    @Override
    public Stream mapLast(final Function mapperForLast) {
        N.requireNonNull(mapperForLast);

        if (maxThreadNum <= 1) {
            return new ParallelIteratorStream<>(sequential().mapLast(mapperForLast).iterator(), closeHandlers, false, null, maxThreadNum, splitor);
        }

        final List> iters = new ArrayList<>(maxThreadNum);

        for (int i = 0; i < maxThreadNum; i++) {
            iters.add(new ExIterator() {
                private Object next = NONE;
                private boolean isLast = false;

                @Override
                public boolean hasNext() {
                    if (next == NONE) {
                        synchronized (elements) {
                            if (elements.hasNext()) {
                                next = elements.next();

                                if (elements.hasNext() == false) {
                                    isLast = true;
                                }
                            }
                        }
                    }

                    return next != NONE;
                }

                @Override
                public T next() {
                    if (next == NONE && hasNext() == false) {
                        throw new NoSuchElementException();
                    }

                    final T result = isLast ? mapperForLast.apply((T) next) : (T) next;
                    next = NONE;
                    return result;
                }
            });
        }

        return new ParallelIteratorStream<>(Stream.parallelConcat(iters, asyncExecutor), closeHandlers, false, null, maxThreadNum, splitor);
    }

    @Override
    public  Stream mapLastOrElse(final Function mapperForLast, final Function mapperForElse) {
        N.requireNonNull(mapperForLast);
        N.requireNonNull(mapperForElse);

        if (maxThreadNum <= 1) {
            return new ParallelIteratorStream<>(sequential().mapLastOrElse(mapperForLast, mapperForElse).iterator(), closeHandlers, false, null, maxThreadNum,
                    splitor);
        }

        final List> iters = new ArrayList<>(maxThreadNum);

        for (int i = 0; i < maxThreadNum; i++) {
            iters.add(new ExIterator() {
                private Object next = NONE;
                private boolean isLast = false;

                @Override
                public boolean hasNext() {
                    if (next == NONE) {
                        synchronized (elements) {
                            if (elements.hasNext()) {
                                next = elements.next();

                                if (elements.hasNext() == false) {
                                    isLast = true;
                                }
                            }
                        }
                    }

                    return next != NONE;
                }

                @Override
                public R next() {
                    if (next == NONE && hasNext() == false) {
                        throw new NoSuchElementException();
                    }

                    final R result = isLast ? mapperForLast.apply((T) next) : mapperForElse.apply((T) next);
                    next = NONE;
                    return result;
                }
            });
        }

        return new ParallelIteratorStream<>(Stream.parallelConcat(iters, asyncExecutor), closeHandlers, false, null, maxThreadNum, splitor);
    }

    @Override
    public CharStream mapToChar(final ToCharFunction mapper) {
        if (maxThreadNum <= 1) {
            return new ParallelIteratorCharStream(sequential().mapToChar(mapper).exIterator(), closeHandlers, false, maxThreadNum, splitor);
        }

        final List> iters = new ArrayList<>(maxThreadNum);

        for (int i = 0; i < maxThreadNum; i++) {
            iters.add(new ExIterator() {
                private Object next = NONE;

                @Override
                public boolean hasNext() {
                    if (next == NONE) {
                        synchronized (elements) {
                            if (elements.hasNext()) {
                                next = elements.next();
                            }
                        }
                    }

                    return next != NONE;
                }

                @Override
                public Character next() {
                    if (next == NONE && hasNext() == false) {
                        throw new NoSuchElementException();
                    }

                    Character result = mapper.applyAsChar((T) next);
                    next = NONE;
                    return result;
                }
            });
        }

        return new ParallelIteratorCharStream(Stream.parallelConcat(iters, asyncExecutor), closeHandlers, false, maxThreadNum, splitor);
    }

    @Override
    public ByteStream mapToByte(final ToByteFunction mapper) {
        if (maxThreadNum <= 1) {
            return new ParallelIteratorByteStream(sequential().mapToByte(mapper).exIterator(), closeHandlers, false, maxThreadNum, splitor);
        }

        final List> iters = new ArrayList<>(maxThreadNum);

        for (int i = 0; i < maxThreadNum; i++) {
            iters.add(new ExIterator() {
                private Object next = NONE;

                @Override
                public boolean hasNext() {
                    if (next == NONE) {
                        synchronized (elements) {
                            if (elements.hasNext()) {
                                next = elements.next();
                            }
                        }
                    }

                    return next != NONE;
                }

                @Override
                public Byte next() {
                    if (next == NONE && hasNext() == false) {
                        throw new NoSuchElementException();
                    }

                    Byte result = mapper.applyAsByte((T) next);
                    next = NONE;
                    return result;
                }
            });
        }

        return new ParallelIteratorByteStream(Stream.parallelConcat(iters, asyncExecutor), closeHandlers, false, maxThreadNum, splitor);
    }

    @Override
    public ShortStream mapToShort(final ToShortFunction mapper) {
        if (maxThreadNum <= 1) {
            return new ParallelIteratorShortStream(sequential().mapToShort(mapper).exIterator(), closeHandlers, false, maxThreadNum, splitor);
        }

        final List> iters = new ArrayList<>(maxThreadNum);

        for (int i = 0; i < maxThreadNum; i++) {
            iters.add(new ExIterator() {
                private Object next = NONE;

                @Override
                public boolean hasNext() {
                    if (next == NONE) {
                        synchronized (elements) {
                            if (elements.hasNext()) {
                                next = elements.next();
                            }
                        }
                    }

                    return next != NONE;
                }

                @Override
                public Short next() {
                    if (next == NONE && hasNext() == false) {
                        throw new NoSuchElementException();
                    }

                    Short result = mapper.applyAsShort((T) next);
                    next = NONE;
                    return result;
                }
            });
        }

        return new ParallelIteratorShortStream(Stream.parallelConcat(iters, asyncExecutor), closeHandlers, false, maxThreadNum, splitor);
    }

    @Override
    public IntStream mapToInt(final ToIntFunction mapper) {
        if (maxThreadNum <= 1) {
            return new ParallelIteratorIntStream(sequential().mapToInt(mapper).exIterator(), closeHandlers, false, maxThreadNum, splitor);
        }

        final List> iters = new ArrayList<>(maxThreadNum);

        for (int i = 0; i < maxThreadNum; i++) {
            iters.add(new ExIterator() {
                private Object next = NONE;

                @Override
                public boolean hasNext() {
                    if (next == NONE) {
                        synchronized (elements) {
                            if (elements.hasNext()) {
                                next = elements.next();
                            }
                        }
                    }

                    return next != NONE;
                }

                @Override
                public Integer next() {
                    if (next == NONE && hasNext() == false) {
                        throw new NoSuchElementException();
                    }

                    Integer result = mapper.applyAsInt((T) next);
                    next = NONE;
                    return result;
                }
            });
        }

        return new ParallelIteratorIntStream(Stream.parallelConcat(iters, asyncExecutor), closeHandlers, false, maxThreadNum, splitor);
    }

    @Override
    public LongStream mapToLong(final ToLongFunction mapper) {
        if (maxThreadNum <= 1) {
            return new ParallelIteratorLongStream(sequential().mapToLong(mapper).exIterator(), closeHandlers, false, maxThreadNum, splitor);
        }

        final List> iters = new ArrayList<>(maxThreadNum);

        for (int i = 0; i < maxThreadNum; i++) {
            iters.add(new ExIterator() {
                private Object next = NONE;

                @Override
                public boolean hasNext() {
                    if (next == NONE) {
                        synchronized (elements) {
                            if (elements.hasNext()) {
                                next = elements.next();
                            }
                        }
                    }

                    return next != NONE;
                }

                @Override
                public Long next() {
                    if (next == NONE && hasNext() == false) {
                        throw new NoSuchElementException();
                    }

                    Long result = mapper.applyAsLong((T) next);
                    next = NONE;
                    return result;
                }
            });
        }

        return new ParallelIteratorLongStream(Stream.parallelConcat(iters, asyncExecutor), closeHandlers, false, maxThreadNum, splitor);
    }

    @Override
    public FloatStream mapToFloat(final ToFloatFunction mapper) {
        if (maxThreadNum <= 1) {
            return new ParallelIteratorFloatStream(sequential().mapToFloat(mapper).exIterator(), closeHandlers, false, maxThreadNum, splitor);
        }

        final List> iters = new ArrayList<>(maxThreadNum);

        for (int i = 0; i < maxThreadNum; i++) {
            iters.add(new ExIterator() {
                private Object next = NONE;

                @Override
                public boolean hasNext() {
                    if (next == NONE) {
                        synchronized (elements) {
                            if (elements.hasNext()) {
                                next = elements.next();
                            }
                        }
                    }

                    return next != NONE;
                }

                @Override
                public Float next() {
                    if (next == NONE && hasNext() == false) {
                        throw new NoSuchElementException();
                    }

                    Float result = mapper.applyAsFloat((T) next);
                    next = NONE;
                    return result;
                }
            });
        }

        return new ParallelIteratorFloatStream(Stream.parallelConcat(iters, asyncExecutor), closeHandlers, false, maxThreadNum, splitor);
    }

    @Override
    public DoubleStream mapToDouble(final ToDoubleFunction mapper) {
        if (maxThreadNum <= 1) {
            return new ParallelIteratorDoubleStream(sequential().mapToDouble(mapper).exIterator(), closeHandlers, false, maxThreadNum, splitor);
        }

        final List> iters = new ArrayList<>(maxThreadNum);

        for (int i = 0; i < maxThreadNum; i++) {
            iters.add(new ExIterator() {
                private Object next = NONE;

                @Override
                public boolean hasNext() {
                    if (next == NONE) {
                        synchronized (elements) {
                            if (elements.hasNext()) {
                                next = elements.next();
                            }
                        }
                    }

                    return next != NONE;
                }

                @Override
                public Double next() {
                    if (next == NONE && hasNext() == false) {
                        throw new NoSuchElementException();
                    }

                    Double result = mapper.applyAsDouble((T) next);
                    next = NONE;
                    return result;
                }
            });
        }

        return new ParallelIteratorDoubleStream(Stream.parallelConcat(iters, asyncExecutor), closeHandlers, false, maxThreadNum, splitor);
    }

    @Override
     Stream flatMap0(final Function> mapper) {
        if (maxThreadNum <= 1) {
            return new ParallelIteratorStream<>(((IteratorStream) sequential()).flatMap0(mapper).iterator(), closeHandlers, false, null, maxThreadNum,
                    splitor);
        }

        final List> iters = new ArrayList<>(maxThreadNum);

        for (int i = 0; i < maxThreadNum; i++) {
            iters.add(new ExIterator() {
                private T next = null;
                private Iterator cur = null;

                @Override
                public boolean hasNext() {
                    while ((cur == null || cur.hasNext() == false) && next != NONE) {
                        synchronized (elements) {
                            if (elements.hasNext()) {
                                next = elements.next();
                            } else {
                                next = (T) NONE;
                                break;
                            }
                        }

                        cur = mapper.apply(next);
                    }

                    return cur != null && cur.hasNext();
                }

                @Override
                public R next() {
                    if ((cur == null || cur.hasNext() == false) && hasNext() == false) {
                        throw new NoSuchElementException();
                    }

                    return cur.next();
                }
            });
        }

        return new ParallelIteratorStream<>(Stream.parallelConcat(iters, asyncExecutor), closeHandlers, false, null, maxThreadNum, splitor);
    }

    @Override
    CharStream flatMapToChar0(final Function mapper) {
        if (maxThreadNum <= 1) {
            return new ParallelIteratorCharStream(((IteratorStream) sequential()).flatMapToChar0(mapper).exIterator(), closeHandlers, false, maxThreadNum,
                    splitor);
        }

        final List> iters = new ArrayList<>(maxThreadNum);

        for (int i = 0; i < maxThreadNum; i++) {
            iters.add(new ExIterator() {
                private T next = null;
                private CharIterator cur = null;

                @Override
                public boolean hasNext() {
                    while ((cur == null || cur.hasNext() == false) && next != NONE) {
                        synchronized (elements) {
                            if (elements.hasNext()) {
                                next = elements.next();
                            } else {
                                next = (T) NONE;
                                break;
                            }
                        }

                        cur = mapper.apply(next);
                    }

                    return cur != null && cur.hasNext();
                }

                @Override
                public Character next() {
                    if ((cur == null || cur.hasNext() == false) && hasNext() == false) {
                        throw new NoSuchElementException();
                    }

                    return cur.nextChar();
                }
            });
        }

        return new ParallelIteratorCharStream(Stream.parallelConcat(iters, asyncExecutor), closeHandlers, false, maxThreadNum, splitor);
    }

    @Override
    ByteStream flatMapToByte0(final Function mapper) {
        if (maxThreadNum <= 1) {
            return new ParallelIteratorByteStream(((IteratorStream) sequential()).flatMapToByte0(mapper).exIterator(), closeHandlers, false, maxThreadNum,
                    splitor);
        }

        final List> iters = new ArrayList<>(maxThreadNum);

        for (int i = 0; i < maxThreadNum; i++) {
            iters.add(new ExIterator() {
                private T next = null;
                private ByteIterator cur = null;

                @Override
                public boolean hasNext() {
                    while ((cur == null || cur.hasNext() == false) && next != NONE) {
                        synchronized (elements) {
                            if (elements.hasNext()) {
                                next = elements.next();
                            } else {
                                next = (T) NONE;
                                break;
                            }
                        }

                        cur = mapper.apply(next);
                    }

                    return cur != null && cur.hasNext();
                }

                @Override
                public Byte next() {
                    if ((cur == null || cur.hasNext() == false) && hasNext() == false) {
                        throw new NoSuchElementException();
                    }

                    return cur.nextByte();
                }
            });
        }

        return new ParallelIteratorByteStream(Stream.parallelConcat(iters, asyncExecutor), closeHandlers, false, maxThreadNum, splitor);
    }

    @Override
    ShortStream flatMapToShort0(final Function mapper) {
        if (maxThreadNum <= 1) {
            return new ParallelIteratorShortStream(((IteratorStream) sequential()).flatMapToShort0(mapper).exIterator(), closeHandlers, false, maxThreadNum,
                    splitor);
        }

        final List> iters = new ArrayList<>(maxThreadNum);

        for (int i = 0; i < maxThreadNum; i++) {
            iters.add(new ExIterator() {
                private T next = null;
                private ShortIterator cur = null;

                @Override
                public boolean hasNext() {
                    while ((cur == null || cur.hasNext() == false) && next != NONE) {
                        synchronized (elements) {
                            if (elements.hasNext()) {
                                next = elements.next();
                            } else {
                                next = (T) NONE;
                                break;
                            }
                        }

                        cur = mapper.apply(next);
                    }

                    return cur != null && cur.hasNext();
                }

                @Override
                public Short next() {
                    if ((cur == null || cur.hasNext() == false) && hasNext() == false) {
                        throw new NoSuchElementException();
                    }

                    return cur.nextShort();
                }
            });
        }

        return new ParallelIteratorShortStream(Stream.parallelConcat(iters, asyncExecutor), closeHandlers, false, maxThreadNum, splitor);
    }

    @Override
    IntStream flatMapToInt0(final Function mapper) {
        if (maxThreadNum <= 1) {
            return new ParallelIteratorIntStream(((IteratorStream) sequential()).flatMapToInt0(mapper).exIterator(), closeHandlers, false, maxThreadNum,
                    splitor);
        }

        final List> iters = new ArrayList<>(maxThreadNum);

        for (int i = 0; i < maxThreadNum; i++) {
            iters.add(new ExIterator() {
                private T next = null;
                private IntIterator cur = null;

                @Override
                public boolean hasNext() {
                    while ((cur == null || cur.hasNext() == false) && next != NONE) {
                        synchronized (elements) {
                            if (elements.hasNext()) {
                                next = elements.next();
                            } else {
                                next = (T) NONE;
                                break;
                            }
                        }

                        cur = mapper.apply(next);
                    }

                    return cur != null && cur.hasNext();
                }

                @Override
                public Integer next() {
                    if ((cur == null || cur.hasNext() == false) && hasNext() == false) {
                        throw new NoSuchElementException();
                    }

                    return cur.nextInt();
                }
            });
        }

        return new ParallelIteratorIntStream(Stream.parallelConcat(iters, asyncExecutor), closeHandlers, false, maxThreadNum, splitor);
    }

    @Override
    LongStream flatMapToLong0(final Function mapper) {
        if (maxThreadNum <= 1) {
            return new ParallelIteratorLongStream(((IteratorStream) sequential()).flatMapToLong0(mapper).exIterator(), closeHandlers, false, maxThreadNum,
                    splitor);
        }

        final List> iters = new ArrayList<>(maxThreadNum);

        for (int i = 0; i < maxThreadNum; i++) {
            iters.add(new ExIterator() {
                private T next = null;
                private LongIterator cur = null;

                @Override
                public boolean hasNext() {
                    while ((cur == null || cur.hasNext() == false) && next != NONE) {
                        synchronized (elements) {
                            if (elements.hasNext()) {
                                next = elements.next();
                            } else {
                                next = (T) NONE;
                                break;
                            }
                        }

                        cur = mapper.apply(next);
                    }

                    return cur != null && cur.hasNext();
                }

                @Override
                public Long next() {
                    if ((cur == null || cur.hasNext() == false) && hasNext() == false) {
                        throw new NoSuchElementException();
                    }

                    return cur.nextLong();
                }
            });
        }

        return new ParallelIteratorLongStream(Stream.parallelConcat(iters, asyncExecutor), closeHandlers, false, maxThreadNum, splitor);
    }

    @Override
    FloatStream flatMapToFloat0(final Function mapper) {
        if (maxThreadNum <= 1) {
            return new ParallelIteratorFloatStream(((IteratorStream) sequential()).flatMapToFloat0(mapper).exIterator(), closeHandlers, false, maxThreadNum,
                    splitor);
        }

        final List> iters = new ArrayList<>(maxThreadNum);

        for (int i = 0; i < maxThreadNum; i++) {
            iters.add(new ExIterator() {
                private T next = null;
                private FloatIterator cur = null;

                @Override
                public boolean hasNext() {
                    while ((cur == null || cur.hasNext() == false) && next != NONE) {
                        synchronized (elements) {
                            if (elements.hasNext()) {
                                next = elements.next();
                            } else {
                                next = (T) NONE;
                                break;
                            }
                        }

                        cur = mapper.apply(next);
                    }

                    return cur != null && cur.hasNext();
                }

                @Override
                public Float next() {
                    if ((cur == null || cur.hasNext() == false) && hasNext() == false) {
                        throw new NoSuchElementException();
                    }

                    return cur.nextFloat();
                }
            });
        }

        return new ParallelIteratorFloatStream(Stream.parallelConcat(iters, asyncExecutor), closeHandlers, false, maxThreadNum, splitor);
    }

    @Override
    DoubleStream flatMapToDouble0(final Function mapper) {
        if (maxThreadNum <= 1) {
            return new ParallelIteratorDoubleStream(((IteratorStream) sequential()).flatMapToDouble0(mapper).exIterator(), closeHandlers, false,
                    maxThreadNum, splitor);
        }

        final List> iters = new ArrayList<>(maxThreadNum);

        for (int i = 0; i < maxThreadNum; i++) {
            iters.add(new ExIterator() {
                private T next = null;
                private DoubleIterator cur = null;

                @Override
                public boolean hasNext() {
                    while ((cur == null || cur.hasNext() == false) && next != NONE) {
                        synchronized (elements) {
                            if (elements.hasNext()) {
                                next = elements.next();
                            } else {
                                next = (T) NONE;
                                break;
                            }
                        }

                        cur = mapper.apply(next);
                    }

                    return cur != null && cur.hasNext();
                }

                @Override
                public Double next() {
                    if ((cur == null || cur.hasNext() == false) && hasNext() == false) {
                        throw new NoSuchElementException();
                    }

                    return cur.nextDouble();
                }
            });
        }

        return new ParallelIteratorDoubleStream(Stream.parallelConcat(iters, asyncExecutor), closeHandlers, false, maxThreadNum, splitor);
    }

    @Override
    public  Stream slidingMap(final BiFunction mapper, final int increment) {
        if (maxThreadNum <= 1) {
            return new ParallelIteratorStream<>(sequential().slidingMap(mapper, increment).iterator(), closeHandlers, false, null, maxThreadNum, splitor);
        }

        final int windowSize = 2;

        N.checkArgument(windowSize > 0 && increment > 0, "'windowSize'=%s and 'increment'=%s must not be less than 1", windowSize, increment);

        final List> iters = new ArrayList<>(maxThreadNum);
        final MutableBoolean isFirst = MutableBoolean.of(true);
        final Holder prev = new Holder<>();

        for (int i = 0; i < maxThreadNum; i++) {
            iters.add(new ExIterator() {
                private Object first = NONE;
                private Object second = NONE;

                @Override
                public boolean hasNext() {
                    if (first == NONE) {
                        synchronized (elements) {
                            if (elements.hasNext()) {
                                if (increment > windowSize && isFirst.isFalse()) {
                                    int skipNum = increment - windowSize;

                                    while (skipNum-- > 0 && elements.hasNext()) {
                                        elements.next();
                                    }
                                }

                                if (elements.hasNext()) {
                                    if (increment == 1) {
                                        first = isFirst.isTrue() ? elements.next() : prev.value();
                                        second = elements.hasNext() ? elements.next() : null;

                                        prev.setValue((T) second);

                                    } else {
                                        first = elements.next();
                                        second = elements.hasNext() ? elements.next() : null;
                                    }
                                }

                                isFirst.setFalse();
                            }
                        }
                    }

                    return first != NONE;
                }

                @Override
                public R next() {
                    if (first == NONE && hasNext() == false) {
                        throw new NoSuchElementException();
                    }

                    final R result = mapper.apply((T) first, second == NONE ? null : (T) second);
                    first = NONE;
                    second = NONE;
                    return result;
                }
            });
        }

        return new ParallelIteratorStream<>(Stream.parallelConcat(iters, asyncExecutor), closeHandlers, false, null, maxThreadNum, splitor);
    }

    @Override
    public  Stream slidingMap(final TriFunction mapper, final int increment) {
        if (maxThreadNum <= 1) {
            return new ParallelIteratorStream<>(sequential().slidingMap(mapper, increment).iterator(), closeHandlers, false, null, maxThreadNum, splitor);
        }

        final int windowSize = 3;

        N.checkArgument(windowSize > 0 && increment > 0, "'windowSize'=%s and 'increment'=%s must not be less than 1", windowSize, increment);

        final List> iters = new ArrayList<>(maxThreadNum);
        final MutableBoolean isFirst = MutableBoolean.of(true);
        final Holder prev = new Holder<>();
        final Holder prev2 = new Holder<>();

        for (int i = 0; i < maxThreadNum; i++) {
            iters.add(new ExIterator() {
                private Object first = NONE;
                private Object second = NONE;
                private Object third = NONE;

                @Override
                public boolean hasNext() {
                    if (first == NONE) {
                        synchronized (elements) {
                            if (elements.hasNext()) {
                                if (increment > windowSize && isFirst.isFalse()) {
                                    int skipNum = increment - windowSize;

                                    while (skipNum-- > 0 && elements.hasNext()) {
                                        elements.next();
                                    }
                                }

                                if (elements.hasNext()) {
                                    if (increment == 1) {
                                        first = isFirst.isTrue() ? elements.next() : prev2.value();
                                        second = isFirst.isTrue() ? (elements.hasNext() ? elements.next() : null) : prev.value();
                                        third = elements.hasNext() ? elements.next() : null;

                                        prev2.setValue((T) second);
                                        prev.setValue((T) third);
                                    } else if (increment == 2) {
                                        first = isFirst.isTrue() ? elements.next() : prev.value();
                                        second = elements.hasNext() ? elements.next() : null;
                                        third = elements.hasNext() ? elements.next() : null;

                                        prev.setValue((T) third);
                                    } else {
                                        first = elements.next();
                                        second = elements.hasNext() ? elements.next() : null;
                                        third = elements.hasNext() ? elements.next() : null;
                                    }
                                }

                                isFirst.setFalse();
                            }
                        }
                    }

                    return first != NONE;
                }

                @Override
                public R next() {
                    if (first == NONE && hasNext() == false) {
                        throw new NoSuchElementException();
                    }

                    final R result = mapper.apply((T) first, second == NONE ? null : (T) second, third == NONE ? null : (T) third);
                    first = NONE;
                    second = NONE;
                    third = NONE;
                    return result;
                }
            });
        }

        return new ParallelIteratorStream<>(Stream.parallelConcat(iters, asyncExecutor), closeHandlers, false, null, maxThreadNum, splitor);
    }

    @Override
    public Stream> split(final int size) {
        return new ParallelIteratorStream<>(sequential().split(size).iterator(), closeHandlers, false, null, maxThreadNum, splitor);
    }

    @Override
    public Stream> splitToList(final int size) {
        return new ParallelIteratorStream<>(sequential().splitToList(size).iterator(), closeHandlers, false, null, maxThreadNum, splitor);
    }

    @Override
    public Stream> splitToSet(final int size) {
        return new ParallelIteratorStream<>(sequential().splitToSet(size).iterator(), closeHandlers, false, null, maxThreadNum, splitor);
    }

    @Override
    public  Stream> split(final U identity, final BiFunction predicate, final Consumer identityUpdate) {
        return new ParallelIteratorStream<>(sequential().split(identity, predicate, identityUpdate).iterator(), closeHandlers, false, null, maxThreadNum,
                splitor);
    }

    @Override
    public  Stream> splitToList(final U identity, final BiFunction predicate,
            final Consumer identityUpdate) {
        return new ParallelIteratorStream<>(sequential().splitToList(identity, predicate, identityUpdate).iterator(), closeHandlers, false, null, maxThreadNum,
                splitor);
    }

    @Override
    public  Stream> splitToSet(final U identity, final BiFunction predicate,
            final Consumer identityUpdate) {
        return new ParallelIteratorStream<>(sequential().splitToSet(identity, predicate, identityUpdate).iterator(), closeHandlers, false, null, maxThreadNum,
                splitor);
    }

    @Override
    public Stream> splitBy(final Predicate where) {
        N.requireNonNull(where);

        final List> testedElements = new ArrayList<>();

        final NullabLe> first = indexed().findFirst(new Predicate>() {
            @Override
            public boolean test(Indexed indexed) {
                synchronized (testedElements) {
                    testedElements.add(indexed);
                }

                return !where.test(indexed.value());
            }
        });

        N.sort(testedElements, INDEXED_COMPARATOR);

        final int n = first.isPresent() ? (int) first.get().index() : testedElements.size();
        final Stream[] a = new Stream[2];

        if (n == testedElements.size()) {
            a[0] = new ArrayStream<>((T[]) testedElements.toArray(), null, sorted, cmp);
            a[1] = Stream.empty();
        } else {
            final List list1 = new ArrayList<>(n);
            final List list2 = new ArrayList<>(testedElements.size() - n);

            for (int i = 0; i < n; i++) {
                list1.add(testedElements.get(i).value());
            }

            for (int i = n, size = testedElements.size(); i < size; i++) {
                list2.add(testedElements.get(i).value());
            }

            a[0] = new ArrayStream<>((T[]) list1.toArray(), null, sorted, cmp);
            a[1] = new IteratorStream<>(elements, null, sorted, cmp);

            if (N.notNullOrEmpty(list2)) {
                if (sorted) {
                    a[1] = new IteratorStream<>(a[1].prepend(Stream.of(list2)).iterator(), null, sorted, cmp);
                } else {
                    a[1] = a[1].prepend(Stream.of(list2));
                }
            }
        }

        return new ParallelArrayStream<>(a, 0, a.length, closeHandlers, false, null, maxThreadNum, splitor);
    }

    @Override
    public Stream> sliding(final int windowSize, final int increment) {
        return new ParallelIteratorStream<>(sequential().sliding(windowSize, increment).iterator(), closeHandlers, false, null, maxThreadNum, splitor);
    }

    @Override
    public Stream> slidingToList(final int windowSize, final int increment) {
        return new ParallelIteratorStream<>(sequential().slidingToList(windowSize, increment).iterator(), closeHandlers, false, null, maxThreadNum, splitor);
    }

    @Override
    public Stream distinctBy(final Function keyExtractor) {
        final Set set = new HashSet<>();

        return filter(new Predicate() {
            @Override
            public boolean test(T value) {
                final Object key = hashKey(keyExtractor.apply(value));

                synchronized (set) {
                    return set.add(key);
                }
            }
        });
    }

    @Override
    public Stream top(int n) {
        return top(n, OBJECT_COMPARATOR);
    }

    @Override
    public Stream top(final int n, final Comparator comparator) {
        return new ParallelIteratorStream<>(sequential().top(n, comparator).iterator(), closeHandlers, sorted, cmp, maxThreadNum, splitor);
    }

    @Override
    public Stream sorted() {
        return sorted(OBJECT_COMPARATOR);
    }

    @Override
    public Stream sorted(final Comparator comparator) {
        if (sorted && isSameComparator(comparator, cmp)) {
            return this;
        }

        return new ParallelIteratorStream<>(new ExIterator() {
            T[] a = null;
            int toIndex = 0;
            int cursor = 0;

            @Override
            public boolean hasNext() {
                if (a == null) {
                    sort();
                }

                return cursor < toIndex;
            }

            @Override
            public T next() {
                if (a == null) {
                    sort();
                }

                if (cursor >= toIndex) {
                    throw new NoSuchElementException();
                }

                return a[cursor++];
            }

            @Override
            public long count() {
                if (a == null) {
                    sort();
                }

                return toIndex - cursor;
            }

            @Override
            public void skip(long n) {
                if (a == null) {
                    sort();
                }

                cursor = n < toIndex - cursor ? cursor + (int) n : toIndex;
            }

            @Override
            public  A[] toArray(A[] b) {
                if (a == null) {
                    sort();
                }

                if (b.getClass().equals(a.getClass()) && b.length < toIndex - cursor) {
                    if (cursor == 0) {
                        return (A[]) a;
                    } else {
                        return (A[]) N.copyOfRange(a, cursor, toIndex);
                    }
                } else {
                    if (b.length < toIndex - cursor) {
                        b = N.newArray(b.getClass().getComponentType(), toIndex - cursor);
                    }

                    N.copy(a, cursor, b, 0, toIndex - cursor);

                    return b;
                }
            }

            private void sort() {
                a = (T[]) elements.toArray(N.EMPTY_OBJECT_ARRAY);
                toIndex = a.length;

                if (comparator == null) {
                    N.parallelSort(a);
                } else {
                    N.parallelSort(a, comparator);
                }
            }
        }, closeHandlers, true, comparator, maxThreadNum, splitor);
    }

    @Override
    public Stream peek(final Consumer action) {
        if (maxThreadNum <= 1) {
            return new ParallelIteratorStream<>(sequential().peek(action).iterator(), closeHandlers, false, null, maxThreadNum, splitor);
        }

        final List> iters = new ArrayList<>(maxThreadNum);

        for (int i = 0; i < maxThreadNum; i++) {
            iters.add(new ExIterator() {
                private Object next = NONE;

                @Override
                public boolean hasNext() {
                    if (next == NONE) {
                        synchronized (elements) {
                            if (elements.hasNext()) {
                                next = elements.next();
                            }
                        }
                    }

                    return next != NONE;
                }

                @Override
                public T next() {
                    if (next == NONE && hasNext() == false) {
                        throw new NoSuchElementException();
                    }

                    final T result = (T) next;
                    action.accept(result);
                    next = NONE;
                    return result;
                }
            });
        }

        return new ParallelIteratorStream<>(Stream.parallelConcat(iters, asyncExecutor), closeHandlers, false, null, maxThreadNum, splitor);
    }

    @Override
    public Stream limit(final long maxSize) {
        if (maxSize < 0) {
            throw new IllegalArgumentException("'maxSize' can't be negative: " + maxSize);
        }

        return new ParallelIteratorStream<>(new ExIterator() {
            private long cnt = 0;

            @Override
            public boolean hasNext() {
                return cnt < maxSize && elements.hasNext();
            }

            @Override
            public T next() {
                if (cnt >= maxSize) {
                    throw new NoSuchElementException();
                }

                cnt++;
                return elements.next();
            }

            @Override
            public void skip(long n) {
                elements.skip(n);
            }
        }, closeHandlers, sorted, cmp, maxThreadNum, splitor);
    }

    @Override
    public Stream skip(final long n) {
        if (n < 0) {
            throw new IllegalArgumentException("The skipped number can't be negative: " + n);
        } else if (n == 0) {
            return this;
        }

        return new ParallelIteratorStream<>(new ExIterator() {
            private boolean skipped = false;

            @Override
            public boolean hasNext() {
                if (skipped == false) {
                    elements.skip(n);
                    skipped = true;
                }

                return elements.hasNext();
            }

            @Override
            public T next() {
                if (skipped == false) {
                    elements.skip(n);
                    skipped = true;
                }

                return elements.next();
            }

            @Override
            public long count() {
                if (skipped == false) {
                    elements.skip(n);
                    skipped = true;
                }

                return elements.count();
            }

            @Override
            public void skip(long n2) {
                if (skipped == false) {
                    elements.skip(n);
                    skipped = true;
                }

                elements.skip(n2);
            }

            @Override
            public  A[] toArray(A[] a) {
                if (skipped == false) {
                    elements.skip(n);
                    skipped = true;
                }

                return elements.toArray(a);
            }
        }, closeHandlers, sorted, cmp, maxThreadNum, splitor);
    }

    @Override
    public void forEach(final Consumer action) {
        if (maxThreadNum <= 1) {
            sequential().forEach(action);
            return;
        }

        final List> futureList = new ArrayList<>(maxThreadNum);
        final Holder eHolder = new Holder<>();

        for (int i = 0; i < maxThreadNum; i++) {
            futureList.add(asyncExecutor.execute(new Runnable() {
                @Override
                public void run() {
                    T next = null;

                    try {
                        while (eHolder.value() == null) {
                            synchronized (elements) {
                                if (elements.hasNext()) {
                                    next = elements.next();
                                } else {
                                    break;
                                }
                            }

                            action.accept(next);
                        }
                    } catch (Throwable e) {
                        setError(eHolder, e);
                    }
                }
            }));
        }

        complete(futureList, eHolder);
    }

    @Override
    public  R forEach(R seed, BiFunction accumulator, BiPredicate conditionToBreak) {
        if (logger.isWarnEnabled()) {
            logger.warn("The 'forEach' with break condition is sequentially executed in parallel stream");
        }

        return sequential().forEach(seed, accumulator, conditionToBreak);
    }

    @Override
    public void forEachPair(final BiConsumer action, final int increment) {
        if (maxThreadNum <= 1) {
            sequential().forEachPair(action, increment);
            return;
        }

        final int windowSize = 2;

        N.checkArgument(windowSize > 0 && increment > 0, "'windowSize'=%s and 'increment'=%s must not be less than 1", windowSize, increment);

        final List> futureList = new ArrayList<>(maxThreadNum);
        final Holder eHolder = new Holder<>();
        final Holder prev = new Holder<>();
        final MutableBoolean isFirst = MutableBoolean.of(true);

        for (int i = 0; i < maxThreadNum; i++) {
            futureList.add(asyncExecutor.execute(new Runnable() {
                private T first = null;
                private T second = null;

                @Override
                public void run() {
                    try {
                        while (eHolder.value() == null) {
                            synchronized (elements) {
                                if (elements.hasNext()) {
                                    if (increment > windowSize && isFirst.isFalse()) {
                                        int skipNum = increment - windowSize;

                                        while (skipNum-- > 0 && elements.hasNext()) {
                                            elements.next();
                                        }

                                        if (elements.hasNext() == false) {
                                            break;
                                        }
                                    }

                                    if (increment == 1) {
                                        first = isFirst.isTrue() ? elements.next() : prev.value();
                                        second = elements.hasNext() ? elements.next() : null;

                                        prev.setValue(second);
                                    } else {
                                        first = elements.next();
                                        second = elements.hasNext() ? elements.next() : null;
                                    }

                                    isFirst.setFalse();
                                } else {
                                    break;
                                }
                            }

                            action.accept(first, second);
                        }
                    } catch (Throwable e) {
                        setError(eHolder, e);
                    }
                }
            }));
        }

        complete(futureList, eHolder);
    }

    @Override
    public void forEachTriple(final TriConsumer action, final int increment) {
        if (maxThreadNum <= 1) {
            sequential().forEachTriple(action, increment);
            return;
        }

        final int windowSize = 3;

        N.checkArgument(windowSize > 0 && increment > 0, "'windowSize'=%s and 'increment'=%s must not be less than 1", windowSize, increment);

        final List> futureList = new ArrayList<>(maxThreadNum);
        final Holder eHolder = new Holder<>();
        final Holder prev = new Holder<>();
        final Holder prev2 = new Holder<>();
        final MutableBoolean isFirst = MutableBoolean.of(true);

        for (int i = 0; i < maxThreadNum; i++) {
            futureList.add(asyncExecutor.execute(new Runnable() {
                private T first = null;
                private T second = null;
                private T third = null;

                @Override
                public void run() {
                    try {
                        while (eHolder.value() == null) {
                            synchronized (elements) {
                                if (elements.hasNext()) {
                                    if (increment > windowSize && isFirst.isFalse()) {
                                        int skipNum = increment - windowSize;

                                        while (skipNum-- > 0 && elements.hasNext()) {
                                            elements.next();
                                        }

                                        if (elements.hasNext() == false) {
                                            break;
                                        }
                                    }

                                    if (increment == 1) {
                                        first = isFirst.isTrue() ? elements.next() : prev2.value();
                                        second = isFirst.isTrue() ? (elements.hasNext() ? elements.next() : null) : prev.value();
                                        third = elements.hasNext() ? elements.next() : null;

                                        prev2.setValue(second);
                                        prev.setValue(third);
                                    } else if (increment == 2) {
                                        first = isFirst.isTrue() ? elements.next() : prev.value();
                                        second = elements.hasNext() ? elements.next() : null;
                                        third = elements.hasNext() ? elements.next() : null;

                                        prev.setValue(third);
                                    } else {
                                        first = elements.next();
                                        second = elements.hasNext() ? elements.next() : null;
                                        third = elements.hasNext() ? elements.next() : null;
                                    }

                                    isFirst.setFalse();
                                } else {
                                    break;
                                }
                            }

                            action.accept(first, second, third);
                        }
                    } catch (Throwable e) {
                        setError(eHolder, e);
                    }
                }
            }));
        }

        complete(futureList, eHolder);
    }

    @Override
    public Object[] toArray() {
        return toArray(N.EMPTY_OBJECT_ARRAY);
    }

    @Override
     A[] toArray(A[] a) {
        return elements.toArray(a);
    }

    @Override
    public  A[] toArray(IntFunction generator) {
        return toArray(generator.apply(0));
    }

    @Override
    public List toList() {
        final List result = new ArrayList<>();

        while (elements.hasNext()) {
            result.add(elements.next());
        }

        return result;
    }

    @Override
    public > R toList(Supplier supplier) {
        final R result = supplier.get();

        while (elements.hasNext()) {
            result.add(elements.next());
        }

        return result;
    }

    @Override
    public Set toSet() {
        final Set result = new HashSet<>();

        while (elements.hasNext()) {
            result.add(elements.next());
        }

        return result;
    }

    @Override
    public > R toSet(Supplier supplier) {
        final R result = supplier.get();

        while (elements.hasNext()) {
            result.add(elements.next());
        }

        return result;
    }

    @Override
    public Multiset toMultiset() {
        final Multiset result = new Multiset<>();

        while (elements.hasNext()) {
            result.add(elements.next());
        }

        return result;
    }

    @Override
    public Multiset toMultiset(Supplier> supplier) {
        final Multiset result = supplier.get();

        while (elements.hasNext()) {
            result.add(elements.next());
        }

        return result;
    }

    @Override
    public LongMultiset toLongMultiset() {
        final LongMultiset result = new LongMultiset<>();

        while (elements.hasNext()) {
            result.add(elements.next());
        }

        return result;
    }

    @Override
    public LongMultiset toLongMultiset(Supplier> supplier) {
        final LongMultiset result = supplier.get();

        while (elements.hasNext()) {
            result.add(elements.next());
        }

        return result;
    }

    @Override
    public > M toMap(Function keyExtractor, Function valueMapper,
            BinaryOperator mergeFunction, Supplier mapFactory) {
        return collect(Collectors.toMap(keyExtractor, valueMapper, mergeFunction, mapFactory));
    }

    @Override
    public > M toMap(final Function classifier, final Collector downstream,
            final Supplier mapFactory) {
        return collect(Collectors.groupingBy(classifier, downstream, mapFactory));
    }

    @Override
    public > Multimap toMultimap(Function keyExtractor,
            Function valueMapper, Supplier> mapFactory) {
        return collect(Collectors.toMultimap(keyExtractor, valueMapper, mapFactory));
    }

    @Override
    public T reduce(final T identity, final BinaryOperator accumulator) {
        if (maxThreadNum <= 1) {
            return sequential().reduce(identity, accumulator);
        }

        final List> futureList = new ArrayList<>(maxThreadNum);
        final Holder eHolder = new Holder<>();

        for (int i = 0; i < maxThreadNum; i++) {
            futureList.add(asyncExecutor.execute(new Callable() {
                @Override
                public T call() {
                    T result = identity;
                    T next = null;

                    try {
                        while (eHolder.value() == null) {
                            synchronized (elements) {
                                if (elements.hasNext()) {
                                    next = elements.next();
                                } else {
                                    break;
                                }
                            }

                            result = accumulator.apply(result, next);
                        }
                    } catch (Throwable e) {
                        setError(eHolder, e);
                    }

                    return result;
                }
            }));
        }

        if (eHolder.value() != null) {
            throw N.toRuntimeException(eHolder.value());
        }

        T result = (T) NONE;

        try {
            for (CompletableFuture future : futureList) {
                if (result == NONE) {
                    result = future.get();
                } else {
                    result = accumulator.apply(result, future.get());
                }
            }
        } catch (Exception e) {
            throw N.toRuntimeException(e);
        }

        return result == NONE ? identity : result;
    }

    @Override
    public NullabLe reduce(final BinaryOperator accumulator) {
        if (maxThreadNum <= 1) {
            return sequential().reduce(accumulator);
        }

        final List> futureList = new ArrayList<>(maxThreadNum);
        final Holder eHolder = new Holder<>();

        for (int i = 0; i < maxThreadNum; i++) {
            futureList.add(asyncExecutor.execute(new Callable() {
                @Override
                public T call() {
                    T result = (T) NONE;
                    T next = null;

                    try {
                        while (eHolder.value() == null) {
                            synchronized (elements) {
                                if (elements.hasNext()) {
                                    next = elements.next();
                                } else {
                                    break;
                                }
                            }

                            result = result == NONE ? next : accumulator.apply(result, next);
                        }
                    } catch (Throwable e) {
                        setError(eHolder, e);
                    }

                    return result;
                }
            }));
        }

        if (eHolder.value() != null) {
            throw N.toRuntimeException(eHolder.value());
        }

        T result = (T) NONE;

        try {
            for (CompletableFuture future : futureList) {
                final T tmp = future.get();

                if (tmp == NONE) {
                    continue;
                } else if (result == NONE) {
                    result = tmp;
                } else {
                    result = accumulator.apply(result, tmp);
                }
            }
        } catch (Exception e) {
            throw N.toRuntimeException(e);
        }

        return result == NONE ? (NullabLe) NullabLe.empty() : NullabLe.of(result);
    }

    @Override
    public  U reduce(final U identity, final BiFunction accumulator, final BinaryOperator combiner) {
        if (maxThreadNum <= 1) {
            return sequential().reduce(identity, accumulator, combiner);
        }

        final List> futureList = new ArrayList<>(maxThreadNum);
        final Holder eHolder = new Holder<>();

        for (int i = 0; i < maxThreadNum; i++) {
            futureList.add(asyncExecutor.execute(new Callable() {
                @Override
                public U call() {
                    U result = identity;
                    T next = null;

                    try {
                        while (eHolder.value() == null) {
                            synchronized (elements) {
                                if (elements.hasNext()) {
                                    next = elements.next();
                                } else {
                                    break;
                                }
                            }

                            result = accumulator.apply(result, next);
                        }
                    } catch (Throwable e) {
                        setError(eHolder, e);
                    }

                    return result;
                }
            }));
        }

        if (eHolder.value() != null) {
            throw N.toRuntimeException(eHolder.value());
        }

        U result = (U) NONE;

        try {
            for (CompletableFuture future : futureList) {
                final U tmp = future.get();

                if (result == NONE) {
                    result = tmp;
                } else {
                    result = combiner.apply(result, tmp);
                }
            }
        } catch (Exception e) {
            throw N.toRuntimeException(e);
        }

        return result == NONE ? identity : result;
    }

    @Override
    public  R collect(final Supplier supplier, final BiConsumer accumulator, final BiConsumer combiner) {
        if (maxThreadNum <= 1) {
            return sequential().collect(supplier, accumulator, combiner);
        }

        final List> futureList = new ArrayList<>(maxThreadNum);
        final Holder eHolder = new Holder<>();

        for (int i = 0; i < maxThreadNum; i++) {
            futureList.add(asyncExecutor.execute(new Callable() {
                @Override
                public R call() {
                    final R container = supplier.get();
                    T next = null;

                    try {
                        while (eHolder.value() == null) {
                            synchronized (elements) {
                                if (elements.hasNext()) {
                                    next = elements.next();
                                } else {
                                    break;
                                }
                            }

                            accumulator.accept(container, next);
                        }
                    } catch (Throwable e) {
                        setError(eHolder, e);
                    }

                    return container;
                }
            }));
        }

        if (eHolder.value() != null) {
            throw N.toRuntimeException(eHolder.value());
        }

        R container = (R) NONE;

        try {
            for (CompletableFuture future : futureList) {
                if (container == NONE) {
                    container = future.get();
                } else {
                    combiner.accept(container, future.get());
                }
            }
        } catch (Exception e) {
            throw N.toRuntimeException(e);
        }

        return container == NONE ? supplier.get() : container;
    }

    @Override
    public  R collect(final Collector collector) {
        if (maxThreadNum <= 1 || sorted || collector.characteristics().contains(Collector.Characteristics.CONCURRENT) == false
                || collector.characteristics().contains(Collector.Characteristics.UNORDERED) == false) {
            return sequential().collect(collector);
        }

        final Supplier supplier = collector.supplier();
        final BiConsumer accumulator = collector.accumulator();
        final BinaryOperator combiner = collector.combiner();
        final Function finisher = collector.finisher();

        final List> futureList = new ArrayList<>(maxThreadNum);
        final Holder eHolder = new Holder<>();

        for (int i = 0; i < maxThreadNum; i++) {
            futureList.add(asyncExecutor.execute(new Callable() {
                @Override
                public A call() {
                    A container = supplier.get();
                    T next = null;

                    try {
                        while (eHolder.value() == null) {
                            synchronized (elements) {
                                if (elements.hasNext()) {
                                    next = elements.next();
                                } else {
                                    break;
                                }
                            }

                            accumulator.accept(container, next);
                        }
                    } catch (Throwable e) {
                        setError(eHolder, e);
                    }

                    return container;
                }
            }));
        }

        if (eHolder.value() != null) {
            throw N.toRuntimeException(eHolder.value());
        }

        A container = (A) NONE;

        try {
            for (CompletableFuture future : futureList) {
                if (container == NONE) {
                    container = future.get();
                } else {
                    combiner.apply(container, future.get());
                }
            }
        } catch (Exception e) {
            throw N.toRuntimeException(e);
        }

        return finisher.apply(container == NONE ? supplier.get() : container);
    }

    @Override
    public NullabLe head() {
        if (tail == null) {
            head = elements.hasNext() ? NullabLe.of(elements.next()) : NullabLe. empty();
            tail = new ParallelIteratorStream<>(elements, closeHandlers, sorted, cmp, maxThreadNum, splitor);
        }

        return head;
    }

    @Override
    public Stream tail() {
        if (tail == null) {
            head = elements.hasNext() ? NullabLe.of(elements.next()) : NullabLe. empty();
            tail = new ParallelIteratorStream<>(elements, closeHandlers, sorted, cmp, maxThreadNum, splitor);
        }

        return tail;
    }

    @Override
    public Stream head2() {
        if (head2 == null) {
            final Object[] a = this.toArray();
            head2 = new ParallelArrayStream<>((T[]) a, 0, a.length == 0 ? 0 : a.length - 1, closeHandlers, sorted, cmp, maxThreadNum, splitor);
            tail2 = a.length == 0 ? NullabLe. empty() : NullabLe.of((T) a[a.length - 1]);
        }

        return head2;
    }

    @Override
    public NullabLe tail2() {
        if (head2 == null) {
            final Object[] a = this.toArray();
            head2 = new ParallelArrayStream<>((T[]) a, 0, a.length == 0 ? 0 : a.length - 1, closeHandlers, sorted, cmp, maxThreadNum, splitor);
            tail2 = a.length == 0 ? NullabLe. empty() : NullabLe.of((T) a[a.length - 1]);
        }

        return tail2;
    }

    @Override
    public Stream last(final int n) {
        N.checkArgument(n >= 0, "'n' can't be negative");

        if (n == 0) {
            return new ParallelIteratorStream<>(ExIterator.EMPTY, closeHandlers, sorted, cmp, maxThreadNum, splitor);
        }

        final Deque dqueue = n <= 1024 ? new ArrayDeque(n) : new LinkedList();

        while (elements.hasNext()) {
            if (dqueue.size() >= n) {
                dqueue.pollFirst();
            }

            dqueue.offerLast(elements.next());
        }

        return new ParallelIteratorStream<>(dqueue.iterator(), closeHandlers, sorted, cmp, maxThreadNum, splitor);
    }

    @Override
    public Stream skipLast(final int n) {
        N.checkArgument(n >= 0, "'n' can't be negative");

        if (n == 0) {
            return this;
        }

        return new ParallelIteratorStream<>(new ExIterator() {
            private Deque dqueue = null;

            @Override
            public boolean hasNext() {
                if (dqueue == null) {
                    dqueue = n <= 1024 ? new ArrayDeque(n) : new LinkedList();

                    while (dqueue.size() < n && elements.hasNext()) {
                        dqueue.offerLast(elements.next());
                    }
                }

                return elements.hasNext();
            }

            @Override
            public T next() {
                if (hasNext() == false) {
                    throw new NoSuchElementException();
                }

                dqueue.offerLast(elements.next());

                return dqueue.pollFirst();
            }

        }, closeHandlers, sorted, cmp, maxThreadNum, splitor);
    }

    @Override
    public NullabLe min(Comparator comparator) {
        if (elements.hasNext() == false) {
            return NullabLe.empty();
        } else if (sorted && isSameComparator(comparator, cmp)) {
            return NullabLe.of(elements.next());
        }

        comparator = comparator == null ? OBJECT_COMPARATOR : comparator;

        return collect(Collectors.minBy(comparator));
    }

    @Override
    public NullabLe max(Comparator comparator) {
        if (elements.hasNext() == false) {
            return NullabLe.empty();
        } else if (sorted && isSameComparator(comparator, cmp)) {
            T next = null;

            while (elements.hasNext()) {
                next = elements.next();
            }

            return NullabLe.of(next);
        }

        comparator = comparator == null ? OBJECT_COMPARATOR : comparator;

        return collect(Collectors.maxBy(comparator));
    }

    @Override
    public NullabLe kthLargest(int k, Comparator comparator) {
        return sequential().kthLargest(k, comparator);
    }

    @Override
    public long count() {
        return elements.count();
    }

    @Override
    public boolean anyMatch(final Predicate predicate) {
        if (maxThreadNum <= 1) {
            return sequential().anyMatch(predicate);
        }

        final List> futureList = new ArrayList<>(maxThreadNum);
        final Holder eHolder = new Holder<>();
        final MutableBoolean result = MutableBoolean.of(false);

        for (int i = 0; i < maxThreadNum; i++) {
            futureList.add(asyncExecutor.execute(new Runnable() {
                @Override
                public void run() {
                    T next = null;

                    try {
                        while (result.isFalse() && eHolder.value() == null) {
                            synchronized (elements) {
                                if (elements.hasNext()) {
                                    next = elements.next();
                                } else {
                                    break;
                                }
                            }

                            if (predicate.test(next)) {
                                result.setTrue();
                                break;
                            }
                        }
                    } catch (Throwable e) {
                        setError(eHolder, e);
                    }
                }
            }));
        }

        complete(futureList, eHolder);

        return result.value();
    }

    @Override
    public boolean allMatch(final Predicate predicate) {
        if (maxThreadNum <= 1) {
            return sequential().allMatch(predicate);
        }

        final List> futureList = new ArrayList<>(maxThreadNum);
        final Holder eHolder = new Holder<>();
        final MutableBoolean result = MutableBoolean.of(true);

        for (int i = 0; i < maxThreadNum; i++) {
            futureList.add(asyncExecutor.execute(new Runnable() {
                @Override
                public void run() {
                    T next = null;

                    try {
                        while (result.isTrue() && eHolder.value() == null) {
                            synchronized (elements) {
                                if (elements.hasNext()) {
                                    next = elements.next();
                                } else {
                                    break;
                                }
                            }

                            if (predicate.test(next) == false) {
                                result.setFalse();
                                break;
                            }
                        }
                    } catch (Throwable e) {
                        setError(eHolder, e);
                    }
                }
            }));
        }

        complete(futureList, eHolder);

        return result.value();
    }

    @Override
    public boolean noneMatch(final Predicate predicate) {
        if (maxThreadNum <= 1) {
            return sequential().noneMatch(predicate);
        }

        final List> futureList = new ArrayList<>(maxThreadNum);
        final Holder eHolder = new Holder<>();
        final MutableBoolean result = MutableBoolean.of(true);

        for (int i = 0; i < maxThreadNum; i++) {
            futureList.add(asyncExecutor.execute(new Runnable() {
                @Override
                public void run() {
                    T next = null;

                    try {
                        while (result.isTrue() && eHolder.value() == null) {
                            synchronized (elements) {
                                if (elements.hasNext()) {
                                    next = elements.next();
                                } else {
                                    break;
                                }
                            }

                            if (predicate.test(next)) {
                                result.setFalse();
                                break;
                            }
                        }
                    } catch (Throwable e) {
                        setError(eHolder, e);
                    }
                }
            }));
        }

        complete(futureList, eHolder);

        return result.value();
    }

    @Override
    public NullabLe findFirst(final Predicate predicate) {
        if (maxThreadNum <= 1) {
            return sequential().findFirst(predicate);
        }

        final List> futureList = new ArrayList<>(maxThreadNum);
        final Holder eHolder = new Holder<>();
        final Holder> resultHolder = new Holder<>();
        final MutableLong index = MutableLong.of(0);

        for (int i = 0; i < maxThreadNum; i++) {
            futureList.add(asyncExecutor.execute(new Runnable() {
                @Override
                public void run() {
                    final Pair pair = new Pair<>();

                    try {
                        while (resultHolder.value() == null && eHolder.value() == null) {
                            synchronized (elements) {
                                if (elements.hasNext()) {
                                    pair.left = index.getAndIncrement();
                                    pair.right = elements.next();
                                } else {
                                    break;
                                }
                            }

                            if (predicate.test(pair.right)) {
                                synchronized (resultHolder) {
                                    if (resultHolder.value() == null || pair.left < resultHolder.value().left) {
                                        resultHolder.setValue(pair.copy());
                                    }
                                }

                                break;
                            }
                        }
                    } catch (Throwable e) {
                        setError(eHolder, e);
                    }
                }
            }));
        }

        complete(futureList, eHolder);

        return resultHolder.value() == null ? (NullabLe) NullabLe.empty() : NullabLe.of(resultHolder.value().right);
    }

    @Override
    public NullabLe findLast(final Predicate predicate) {
        if (maxThreadNum <= 1) {
            return sequential().findLast(predicate);
        }

        final List> futureList = new ArrayList<>(maxThreadNum);
        final Holder eHolder = new Holder<>();
        final Holder> resultHolder = new Holder<>();
        final MutableLong index = MutableLong.of(0);

        for (int i = 0; i < maxThreadNum; i++) {
            futureList.add(asyncExecutor.execute(new Runnable() {
                @Override
                public void run() {
                    final Pair pair = new Pair<>();

                    try {
                        while (eHolder.value() == null) {
                            synchronized (elements) {
                                if (elements.hasNext()) {
                                    pair.left = index.getAndIncrement();
                                    pair.right = elements.next();
                                } else {
                                    break;
                                }
                            }

                            if (predicate.test(pair.right)) {
                                synchronized (resultHolder) {
                                    if (resultHolder.value() == null || pair.left > resultHolder.value().left) {
                                        resultHolder.setValue(pair.copy());
                                    }
                                }
                            }
                        }
                    } catch (Throwable e) {
                        setError(eHolder, e);
                    }
                }
            }));
        }

        complete(futureList, eHolder);

        return resultHolder.value() == null ? (NullabLe) NullabLe.empty() : NullabLe.of(resultHolder.value().right);
    }

    @Override
    public NullabLe findAny(final Predicate predicate) {
        if (maxThreadNum <= 1) {
            return sequential().findAny(predicate);
        }

        final List> futureList = new ArrayList<>(maxThreadNum);
        final Holder eHolder = new Holder<>();
        final Holder resultHolder = Holder.of((T) NONE);

        for (int i = 0; i < maxThreadNum; i++) {
            futureList.add(asyncExecutor.execute(new Runnable() {
                @Override
                public void run() {
                    T next = null;

                    try {
                        while (resultHolder.value() == NONE && eHolder.value() == null) {
                            synchronized (elements) {
                                if (elements.hasNext()) {
                                    next = elements.next();
                                } else {
                                    break;
                                }
                            }

                            if (predicate.test(next)) {
                                synchronized (resultHolder) {
                                    if (resultHolder.value() == NONE) {
                                        resultHolder.setValue(next);
                                    }
                                }

                                break;
                            }
                        }
                    } catch (Throwable e) {
                        setError(eHolder, e);
                    }
                }
            }));
        }

        complete(futureList, eHolder);

        return resultHolder.value() == NONE ? (NullabLe) NullabLe.empty() : NullabLe.of(resultHolder.value());
    }

    @Override
    public Stream intersection(final Function mapper, final Collection c) {
        if (maxThreadNum <= 1) {
            return new ParallelIteratorStream<>(sequential().intersection(mapper, c).iterator(), closeHandlers, sorted, cmp, maxThreadNum, splitor);
        }

        final Multiset multiset = Multiset.from(c);

        return filter(new Predicate() {
            @Override
            public boolean test(T value) {
                final Object key = mapper.apply(value);

                synchronized (multiset) {
                    return multiset.getAndRemove(key) > 0;
                }
            }
        });
    }

    @Override
    public Stream difference(final Function mapper, final Collection c) {
        if (maxThreadNum <= 1) {
            return new ParallelIteratorStream<>(sequential().intersection(mapper, c).iterator(), closeHandlers, sorted, cmp, maxThreadNum, splitor);
        }

        final Multiset multiset = Multiset.from(c);

        return filter(new Predicate() {
            @Override
            public boolean test(T value) {
                final Object key = mapper.apply(value);

                synchronized (multiset) {
                    return multiset.getAndRemove(key) < 1;
                }
            }
        });
    }

    @Override
    public Stream queued(int queueSize) {
        final Iterator iter = iterator();

        if (iter instanceof QueuedIterator && ((QueuedIterator) iter).max() >= queueSize) {
            return this;
        } else {
            return new ParallelIteratorStream<>(Stream.parallelConcat(Arrays.asList(iter), queueSize, asyncExecutor), closeHandlers, sorted, cmp, maxThreadNum,
                    splitor);
        }
    }

    @Override
    public Stream append(Stream stream) {
        return new ParallelIteratorStream<>(Stream.concat(this, stream), closeHandlers, false, null, maxThreadNum, splitor);
    }

    @Override
    public Stream prepend(Stream stream) {
        return new ParallelIteratorStream<>(Stream.concat(stream, this), closeHandlers, false, null, maxThreadNum, splitor);
    }

    @Override
    public Stream merge(final Stream b, final BiFunction nextSelector) {
        return new ParallelIteratorStream<>(Stream.merge(this, b, nextSelector), closeHandlers, false, null, maxThreadNum, splitor);
    }

    @Override
    public  Stream zipWith(Stream b, BiFunction zipFunction) {
        return new ParallelIteratorStream<>(Stream.zip(this, b, zipFunction), closeHandlers, false, null, maxThreadNum, splitor);
    }

    @Override
    public  Stream zipWith(Stream b, Stream c, TriFunction zipFunction) {
        return new ParallelIteratorStream<>(Stream.zip(this, b, c, zipFunction), closeHandlers, false, null, maxThreadNum, splitor);
    }

    @Override
    public  Stream zipWith(Stream b, T valueForNoneA, T2 valueForNoneB, BiFunction zipFunction) {
        return new ParallelIteratorStream<>(Stream.zip(this, b, valueForNoneA, valueForNoneB, zipFunction), closeHandlers, false, null, maxThreadNum, splitor);
    }

    @Override
    public  Stream zipWith(Stream b, Stream c, T valueForNoneA, T2 valueForNoneB, T3 valueForNoneC,
            TriFunction zipFunction) {
        return new ParallelIteratorStream<>(Stream.zip(this, b, c, valueForNoneA, valueForNoneB, valueForNoneC, zipFunction), closeHandlers, false, null,
                maxThreadNum, splitor);
    }

    @Override
    public long persist(final PreparedStatement stmt, final int batchSize, final int batchInterval,
            final Try.BiConsumer stmtSetter) {
        N.checkArgument(batchSize > 0 && batchInterval >= 0, "'batchSize'=%s must be greater than 0 and 'batchInterval'=%s can't be negative", batchSize,
                batchInterval);

        if (maxThreadNum <= 1) {
            return sequential().persist(stmt, batchSize, batchInterval, stmtSetter);
        }

        final List> futureList = new ArrayList<>(maxThreadNum);
        final Holder eHolder = new Holder<>();
        final AtomicLong result = new AtomicLong();

        for (int i = 0; i < maxThreadNum; i++) {
            futureList.add(asyncExecutor.execute(new Runnable() {
                @Override
                public void run() {
                    long cnt = 0;
                    T next = null;

                    try {
                        while (eHolder.value() == null) {
                            synchronized (elements) {
                                if (elements.hasNext()) {
                                    next = elements.next();
                                } else {
                                    break;
                                }
                            }

                            stmtSetter.accept(stmt, next);
                            stmt.addBatch();

                            if ((++cnt % batchSize) == 0) {
                                stmt.executeBatch();
                                stmt.clearBatch();

                                if (batchInterval > 0) {
                                    N.sleep(batchInterval);
                                }
                            }
                        }

                        if ((cnt % batchSize) > 0) {
                            stmt.executeBatch();
                            stmt.clearBatch();
                        }

                        result.addAndGet(cnt);
                    } catch (Throwable e) {
                        setError(eHolder, e);
                    }
                }
            }));
        }

        complete(futureList, eHolder);

        return result.longValue();
    }

    @Override
    public boolean isParallel() {
        return true;
    }

    @Override
    public Stream sequential() {
        IteratorStream tmp = sequential;

        if (tmp == null) {
            tmp = new IteratorStream<>(elements, closeHandlers, sorted, cmp);
            sequential = tmp;
        }

        return tmp;
    }

    @Override
    public Stream parallel(int maxThreadNum, Splitor splitor) {
        if (maxThreadNum < 1 || maxThreadNum > MAX_THREAD_NUM_PER_OPERATION) {
            throw new IllegalArgumentException("'maxThreadNum' must not less than 1 or exceeded: " + MAX_THREAD_NUM_PER_OPERATION);
        }

        if (this.maxThreadNum == maxThreadNum && this.splitor == splitor) {
            return this;
        }

        return new ParallelIteratorStream<>(elements, closeHandlers, sorted, cmp, maxThreadNum, splitor);
    }

    @Override
    public int maxThreadNum() {
        return maxThreadNum;
    }

    @Override
    public Stream maxThreadNum(int maxThreadNum) {
        if (maxThreadNum < 1 || maxThreadNum > MAX_THREAD_NUM_PER_OPERATION) {
            throw new IllegalArgumentException("'maxThreadNum' must not less than 1 or exceeded: " + MAX_THREAD_NUM_PER_OPERATION);
        }

        if (this.maxThreadNum == maxThreadNum) {
            return this;
        }

        return new ParallelIteratorStream<>(elements, closeHandlers, sorted, cmp, maxThreadNum, splitor);
    }

    @Override
    public Splitor splitor() {
        return splitor;
    }

    @Override
    public Stream splitor(Splitor splitor) {
        if (this.splitor == splitor) {
            return this;
        }

        return new ParallelIteratorStream<>(elements, closeHandlers, sorted, cmp, maxThreadNum, splitor);
    }

    @Override
    public Stream onClose(Runnable closeHandler) {
        final Set newCloseHandlers = new LocalLinkedHashSet<>(N.isNullOrEmpty(this.closeHandlers) ? 1 : this.closeHandlers.size() + 1);

        if (N.notNullOrEmpty(this.closeHandlers)) {
            newCloseHandlers.addAll(this.closeHandlers);
        }

        newCloseHandlers.add(closeHandler);

        return new ParallelIteratorStream<>(elements, newCloseHandlers, sorted, cmp, maxThreadNum, splitor);
    }
}