001/*
002 * Java Genetic Algorithm Library (jenetics-8.1.0).
003 * Copyright (c) 2007-2024 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 * {@snippet lang="java":
037 * final Accumulator<Integer, ?, List<Integer>> accu =
038 *     Accumulator.of(Collectors.toList());
039 *
040 * final ISeq<List<Integer>> result = IntStream.range(0, 10).boxed()
041 *     .peek(accu)
042 *     .map(i -> accu.result())
043 *     .collect(ISeq.toISeq());
044 *
045 * result.forEach(System.out::println);
046 * }
047 * The code above gives you the following output.
048 * <pre>
049 * [0]
050 * [0,1]
051 * [0,1,2]
052 * [0,1,2,3]
053 * [0,1,2,3,4]
054 * [0,1,2,3,4,5]
055 * [0,1,2,3,4,5,6]
056 * [0,1,2,3,4,5,6,7]
057 * [0,1,2,3,4,5,6,7,8]
058 * [0,1,2,3,4,5,6,7,8,9]
059 * </pre>
060 *
061 * @apiNote
062 * In contrast to the {@link Collector} interface, the {@code Accumulator} is
063 * not mergeable. The <em>accumulator</em> is not thread-safe and can't be used
064 * for parallel streams when used as {@link Consumer} in the
065 * {@link java.util.stream.Stream#peek(Consumer)} or
066 * {@link java.util.stream.Stream#forEach(Consumer)} method. Obtaining a
067 * synchronized view of the accumulator with the {@link #synced()} method, will
068 * solve this problem. If the accumulator is used as {@link Collector}, the
069 * usage in parallel streams is safe.
070 *
071 * @param <T> the type of input elements to the accumulate operation
072 * @param <A> the accumulator type
073 * @param <R> the result type of the accumulated operation
074 *
075 * @author <a href="mailto:franz.wilhelmstoetter@gmail.com">Franz Wilhelmstötter</a>
076 * @version 6.1
077 * @since 6.1
078 */
079public interface Accumulator<T, A extends Accumulator<T, A, R>, R>
080        extends Consumer<T>, Collector<T, A, R>
081{
082
083        /**
084         * Return a <em>copy</em>  of the current result of the accumulated elements.
085         * The accumulated elements are not changed by this method.
086         *
087         * @return the current result of the accumulated elements
088         */
089        R result();
090
091        /**
092         * Combines {@code this} accumulator with the {@code other} one.
093         *
094         * @param other the other accumulator
095         * @return the combined accumulator
096         * @throws UnsupportedOperationException unless it's overridden by the
097         *         implementation
098         */
099        default A combine(final A other) {
100                throw new UnsupportedOperationException(
101                        "No implementation for combining accumulators."
102                );
103        }
104
105        @Override
106        default BiConsumer<A, T> accumulator() {
107                return A::accept;
108        }
109
110        @Override
111        default BinaryOperator<A> combiner() {
112                return A::combine;
113        }
114
115        @Override
116        default Function<A, R> finisher() {
117                return A::result;
118        }
119
120        @Override
121        default Set<Characteristics> characteristics() {
122                return Set.of();
123        }
124
125        /**
126         * Returns a synchronized (thread-safe) accumulator backed by {@code this}
127         * accumulator. The given {@code lock} is used as a synchronization object.
128         *
129         * @param lock the <em>lock</em> used for synchronization
130         * @return a synchronized (thread-safe) accumulator backed by {@code this}
131         *             accumulator
132         * @throws NullPointerException if the given {@code lock} is {@code null}
133         */
134        default Accumulator<T, ?, R> synced(final Object lock) {
135                requireNonNull(lock);
136
137                @SuppressWarnings("unchecked")
138                final A self = (A)this;
139                return this instanceof SynchronizedAccumulator
140                        ? this
141                        : new SynchronizedAccumulator<>(self, lock);
142        }
143
144        /**
145         * Returns a synchronized (thread-safe) accumulator backed by {@code this}
146         * accumulator. {@code this} accumulator is used as a synchronization object.
147         *
148         * @return a synchronized (thread-safe) accumulator backed by {@code this}
149         *             accumulator
150         */
151        default Accumulator<T, ?, R> synced() {
152                return synced(this);
153        }
154
155        /**
156         * Create a new accumulator from the given {@code collector}.
157         * {@snippet lang="java":
158         * final Accumulator<Integer, ?, ISeq<Integer>> accu =
159         *     Accumulator.of(ISeq.toISeq());
160         * }
161         *
162         * @param collector the collector which is used for accumulation and creation
163         *        the result value.
164         * @param <T> the type of input elements to the reduction operation
165         * @param <R> the result type of the reduction operation
166         * @return a new accumulator which is backed by the given {@code collector}
167         * @throws NullPointerException if the given {@code collector} is {@code null}
168         */
169        static <T, R> Accumulator<T, ?, R> of(final Collector<T, ?, R> collector) {
170                return new CollectorAccumulator<>(collector);
171        }
172
173}
174