001/*
002 * Java Genetic Algorithm Library (jenetics-7.2.0).
003 * Copyright (c) 2007-2023 Franz Wilhelmstötter
004 *
005 * Licensed under the Apache License, Version 2.0 (the "License");
006 * you may not use this file except in compliance with the License.
007 * You may obtain a copy of the License at
008 *
009 *      http://www.apache.org/licenses/LICENSE-2.0
010 *
011 * Unless required by applicable law or agreed to in writing, software
012 * distributed under the License is distributed on an "AS IS" BASIS,
013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014 * See the License for the specific language governing permissions and
015 * limitations under the License.
016 *
017 * Author:
018 *    Franz Wilhelmstötter (franz.wilhelmstoetter@gmail.com)
019 */
020package io.jenetics.util;
021
022import static java.util.Objects.requireNonNull;
023
024import java.util.Set;
025import java.util.function.BiConsumer;
026import java.util.function.BinaryOperator;
027import java.util.function.Consumer;
028import java.util.function.Function;
029import java.util.stream.Collector;
030
031/**
032 * This interface lets you accumulate elements of type {@code T} to a result of
033 * type {@code R}.  In contrast to a {@link Collector} an {@code Accumulator}
034 * can deliver intermediate results while accumulating. An accumulator can be
035 * created from any {@link Collector} with the ({@link #of(Collector)}) method.
036 *
037 * <pre>{@code
038 * final Accumulator<Integer, ?, List<Integer>> accu =
039 *     Accumulator.of(Collectors.toList());
040 *
041 * final ISeq<List<Integer>> result = IntStream.range(0, 10).boxed()
042 *     .peek(accu)
043 *     .map(i -> accu.result())
044 *     .collect(ISeq.toISeq());
045 *
046 * result.forEach(System.out::println);
047 * }</pre>
048 * The code above gives you the following output.
049 * <pre>
050 * [0]
051 * [0,1]
052 * [0,1,2]
053 * [0,1,2,3]
054 * [0,1,2,3,4]
055 * [0,1,2,3,4,5]
056 * [0,1,2,3,4,5,6]
057 * [0,1,2,3,4,5,6,7]
058 * [0,1,2,3,4,5,6,7,8]
059 * [0,1,2,3,4,5,6,7,8,9]
060 * </pre>
061 *
062 * @apiNote
063 * In contrast to the {@link Collector} interface, the {@code Accumulator} is
064 * not mergeable. The <em>accumulator</em> is not thread-safe and can't be used
065 * for parallel streams when used as {@link Consumer} in the
066 * {@link java.util.stream.Stream#peek(Consumer)} or
067 * {@link java.util.stream.Stream#forEach(Consumer)} method. Obtaining a
068 * synchronized view of the accumulator with the {@link #synced()} method, will
069 * solve this problem. If the accumulator is used as {@link Collector}, the
070 * usage in parallel streams is safe.
071 *
072 * @param <T> the type of input elements to the accumulate operation
073 * @param <A> the accumulator type
074 * @param <R> the result type of the accumulated operation
075 *
076 * @author <a href="mailto:franz.wilhelmstoetter@gmail.com">Franz Wilhelmstötter</a>
077 * @version 6.1
078 * @since 6.1
079 */
080public interface Accumulator<T, A extends Accumulator<T, A, R>, R>
081        extends Consumer<T>, Collector<T, A, R>
082{
083
084        /**
085         * Return a <em>copy</em>  of the current result of the accumulated elements.
086         * The accumulated elements are not changed by this method.
087         *
088         * @return the current result of the accumulated elements
089         */
090        R result();
091
092        /**
093         * Combines {@code this} accumulator with the {@code other} one.
094         *
095         * @param other the other accumulator
096         * @return the combined accumulator
097         * @throws UnsupportedOperationException unless it's overridden by the
098         *         implementation
099         */
100        default A combine(final A other) {
101                throw new UnsupportedOperationException(
102                        "No implementation for combining accumulators."
103                );
104        }
105
106        @Override
107        default BiConsumer<A, T> accumulator() {
108                return A::accept;
109        }
110
111        @Override
112        default BinaryOperator<A> combiner() {
113                return A::combine;
114        }
115
116        @Override
117        default Function<A, R> finisher() {
118                return A::result;
119        }
120
121        @Override
122        default Set<Characteristics> characteristics() {
123                return Set.of();
124        }
125
126        /**
127         * Returns a synchronized (thread-safe) accumulator backed by {@code this}
128         * accumulator. The given {@code lock} is used as a synchronization object.
129         *
130         * @param lock the <em>lock</em> used for synchronization
131         * @return a synchronized (thread-safe) accumulator backed by {@code this}
132         *             accumulator
133         * @throws NullPointerException if the given {@code lock} is {@code null}
134         */
135        default Accumulator<T, ?, R> synced(final Object lock) {
136                requireNonNull(lock);
137
138                @SuppressWarnings("unchecked")
139                final A self = (A)this;
140                return this instanceof SynchronizedAccumulator
141                        ? this
142                        : new SynchronizedAccumulator<>(self, lock);
143        }
144
145        /**
146         * Returns a synchronized (thread-safe) accumulator backed by {@code this}
147         * accumulator. {@code this} accumulator is used as a synchronization object.
148         *
149         * @return a synchronized (thread-safe) accumulator backed by {@code this}
150         *             accumulator
151         */
152        default Accumulator<T, ?, R> synced() {
153                return synced(this);
154        }
155
156        /**
157         * Create a new accumulator from the given {@code collector}.
158         *
159         * <pre>{@code
160         * final Accumulator<Integer, ?, ISeq<Integer>> accu =
161         *     Accumulator.of(ISeq.toISeq());
162         * }</pre>
163         *
164         * @param collector the collector which is used for accumulation and creation
165         *        the result value.
166         * @param <T> the type of input elements to the reduction operation
167         * @param <R> the result type of the reduction operation
168         * @return a new accumulator which is backed by the given {@code collector}
169         * @throws NullPointerException if the given {@code collector} is {@code null}
170         */
171        static <T, R> Accumulator<T, ?, R> of(final Collector<T, ?, R> collector) {
172                return new CollectorAccumulator<>(collector);
173        }
174
175}
176