View Javadoc

1   /*
2      Copyright 2011 Atlassian
3   
4      Licensed under the Apache License, Version 2.0 (the "License");
5      you may not use this file except in compliance with the License.
6      You may obtain a copy of the License at
7   
8          http://www.apache.org/licenses/LICENSE-2.0
9   
10     Unless required by applicable law or agreed to in writing, software
11     distributed under the License is distributed on an "AS IS" BASIS,
12     WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13     See the License for the specific language governing permissions and
14     limitations under the License.
15   */
16  
17  package io.atlassian.fugue;
18  
19  import static io.atlassian.fugue.Functions.countingPredicate;
20  import static io.atlassian.fugue.Iterators.emptyIterator;
21  import static io.atlassian.fugue.Iterators.peekingIterator;
22  import static io.atlassian.fugue.Option.none;
23  import static io.atlassian.fugue.Option.some;
24  import static io.atlassian.fugue.Pair.leftValue;
25  import static io.atlassian.fugue.Pair.pair;
26  import static io.atlassian.fugue.Pair.rightValue;
27  import static io.atlassian.fugue.Suppliers.ofInstance;
28  import static java.util.Arrays.asList;
29  import static java.util.Collections.unmodifiableCollection;
30  import static java.util.Objects.requireNonNull;
31  
32  import java.io.Serializable;
33  import java.lang.ref.Reference;
34  import java.lang.ref.WeakReference;
35  import java.util.Arrays;
36  import java.util.Collection;
37  import java.util.Comparator;
38  import java.util.Iterator;
39  import java.util.LinkedList;
40  import java.util.List;
41  import java.util.NoSuchElementException;
42  import java.util.Queue;
43  import java.util.TreeSet;
44  import java.util.concurrent.CancellationException;
45  import java.util.concurrent.ExecutionException;
46  import java.util.concurrent.locks.AbstractQueuedSynchronizer;
47  import java.util.function.BiFunction;
48  import java.util.function.Function;
49  import java.util.function.Predicate;
50  import java.util.function.Supplier;
51  import java.util.stream.Collector;
52  import java.util.stream.StreamSupport;
53  
54  /**
55   * Contains static utility methods that operate on or return objects of type
56   * {code}Iterable{code}.
57   *
58   * The iterables produced from the functions in this class are safe to reuse
59   * multiple times. Iterables#iterator returns a new iterator each time.
60   *
61   * @since 1.0
62   */
63  public class Iterables {
64    private Iterables() {
65      throw new UnsupportedOperationException("This class is not instantiable.");
66    }
67  
68    static final Iterable<?> EMPTY = new Iterable<Object>() {
69      @Override public Iterator<Object> iterator() {
70        return emptyIterator();
71      }
72  
73      @Override public String toString() {
74        return "[]";
75      }
76    };
77  
78    /**
79     * Returns an empty iterable, that is, an {@code Iterable} with an
80     * {@code Iterator} for which {@code hasNext()} always returns {@code false},
81     * and the other methods throw appropriate exceptions if called.
82     *
83     * Intended to be used as a more idiomatic replacement for
84     * {@code Collections.emptyList()} in code that otherwise deals only with
85     * iterables.
86     *
87     * @param <T> the type
88     * @return an empty iterable
89     * @since 1.2
90     */
91    public static <T> Iterable<T> emptyIterable() {
92      @SuppressWarnings("unchecked")
93      final Iterable<T> result = (Iterable<T>) EMPTY;
94      return result;
95    }
96  
97    /**
98     * Creates an Iterable from the underlying array of elements.
99     *
100    * @param <A> The type of the elements
101    * @param as the elements to iterate over
102    * @return an Iterable across the underlying elements
103    * @since 2.3
104    */
105   @SafeVarargs public static <A> Iterable<A> iterable(final A... as) {
106     return unmodifiableCollection(asList(as));
107   }
108 
109   /**
110    * Finds the first item that matches the predicate. Traditionally, this should
111    * be named find; in this case it is named findFirst to avoid clashing with
112    * static imports from Guava's com.google.common.collect.Iterables.
113    *
114    * @param <T> the type
115    * @param elements the iterable to search for a matching element
116    * @param p the predicate to use to determine if an element is eligible to be
117    * returned
118    * @return the first item in elements that matches predicate
119    * @since 1.0
120    */
121   public static <T> Option<T> findFirst(final Iterable<? extends T> elements, final Predicate<? super T> p) {
122     for (final T t : filter(elements, p)) {
123       return some(t);
124     }
125     return none();
126   }
127 
128   /**
129    * Partial application of the predicate argument to
130    * {@link #findFirst(Iterable, Predicate)} returning a function that takes an
131    * {@link java.lang.Iterable} as its argument
132    *
133    * @param <A> the type
134    * @param predicate the predicate to use to determine if an element is
135    * eligible to be returned
136    * @return a Function that takes an {@link java.lang.Iterable} as its
137    * argument, and returns the first element that satisfies the predicate
138    * @since 2.2
139    */
140   public static <A> Function<Iterable<A>, Option<A>> findFirst(final Predicate<? super A> predicate) {
141     return input -> findFirst(input, predicate);
142   }
143 
144   /**
145    * If {@code as} is empty, returns {@code none()}. Otherwise, returns
146    * {@code some(get(as, 0))}.
147    *
148    * @param <A> type of elements in {@code as}
149    * @param as elements to get the first value of, must not be null
150    * @return {@code none()} if {@code as} is empty. {@code some(get(as, 0))}
151    * otherwise
152    * @since 1.1
153    */
154   public static <A> Option<A> first(final Iterable<A> as) {
155     for (final A a : as) {
156       return some(a);
157     }
158     return none();
159   }
160 
161   /**
162    * Performs function application within an iterable (applicative functor
163    * pattern).
164    *
165    * @param as an iterable
166    * @param fs The iterable of functions to apply.
167    * @return A new iterable after applying the given stream of functions through
168    * as.
169    */
170   public static <A, B> Iterable<B> ap(final Iterable<A> as, final Iterable<Function<A, B>> fs) {
171     return flatMap(fs, f -> map(as, f));
172   }
173 
174   /**
175    * Applies {@code f} to each element of {@code collection}, then concatenates
176    * the result.
177    *
178    * @param <A> type of elements in {@code collection}
179    * @param <B> type elements in the new {@code Iterable} {@code f} will
180    * transform elements to
181    * @param collection elements to apply {@code f} to
182    * @param f {@code Function} to apply to elements of {@code collection}
183    * @return concatenated result of applying {@code f} to each element of
184    * {@code collection}
185    * @since 1.1
186    */
187   public static <A, B> Iterable<B> flatMap(final Iterable<A> collection, final Function<? super A, ? extends Iterable<? extends B>> f) {
188     return join(map(collection, f));
189   }
190 
191   /**
192    * Applies each function in {@code fs} to {@code arg}.
193    *
194    * @param <A> the argument type
195    * @param <B> the function output and type of the elements of the final
196    * iterable.
197    * @param fs an iterable of functions that the arg will be applied to
198    * @param arg the argument to apply to the functions
199    * @return the results of the functions when applied to the arg
200    * @since 1.1
201    */
202   public static <A, B> Iterable<B> revMap(final Iterable<? extends Function<A, B>> fs, final A arg) {
203     return map(fs, Functions.<A, B> apply(arg));
204   }
205 
206   /**
207    * Predicate that checks if an iterable is empty.
208    *
209    * @return {@code Predicate} which checks if an {@code Iterable} is empty
210    * @since 1.1
211    */
212   public static Predicate<Iterable<?>> isEmpty() {
213     return it -> {
214       if (it instanceof Collection) {
215         return ((Collection<?>) it).isEmpty();
216       }
217       return !it.iterator().hasNext();
218     };
219   }
220 
221   /**
222    * Filters and maps (aka transforms) the unfiltered iterable.
223    *
224    * Applies the given partial function to each element of the unfiltered
225    * iterable. If the application returns none, the element will be left out;
226    * otherwise, the transformed object contained in the Option will be added to
227    * the result.
228    *
229    * @param <A> the input type
230    * @param <B> the output type
231    * @param from the input iterable, must not be null and must not contain null
232    * @param partial the collecting function
233    * @return the collected iterable
234    * @since 2.2
235    */
236   public static <A, B> Iterable<B> collect(final Iterable<? extends A> from, final Function<? super A, Option<B>> partial) {
237     return new CollectingIterable<>(from, partial);
238   }
239 
240   /**
241    * Uses a {@link java.util.stream.Collector} to collect/reduce an
242    * {@link java.lang.Iterable}.
243    *
244    * @param elements the iterable to run the Collector on. Can not be null.
245    * @param collector the {@link java.util.stream.Collector}. Can not be null.
246    * @param <T> the type of elements in the original {@link java.lang.Iterable}
247    * @param <A> accumulator type
248    * @param <R> return type
249    * @return the result of the reduction, using the given
250    * {@link java.util.stream.Collector}
251    * @see Collector javadocs for more details on how to use Collectors.
252    * @since 3.1
253    */
254   public static <T, A, R> R collect(final Iterable<T> elements, final Collector<T, A, R> collector) {
255     requireNonNull(elements, "elements is null.");
256     requireNonNull(collector, "collector is null.");
257     return StreamSupport.stream(elements.spliterator(), false).collect(collector);
258   }
259 
260   /**
261    * Filter an {@code Iterable} into a {@code Pair} of {@code Iterable}'s.
262    *
263    * @param <A> the type
264    * @param iterable to be filtered
265    * @param p to filter each element
266    * @return a pair where the left matches the predicate, and the right does
267    * not.
268    * @since 1.2
269    */
270   public static <A> Pair<Iterable<A>, Iterable<A>> partition(final Iterable<A> iterable, final Predicate<? super A> p) {
271     return pair(filter(iterable, p), filter(iterable, p.negate()));
272   }
273 
274   /**
275    * Aakes the first {@code n} {@code as} and returns them.
276    *
277    * @param <A> type of {@code as}
278    * @param n number of {@code as} to take, must greater than or equal to zero
279    * @param as list of values, must not be null and must not contain null
280    * @return first {@code n} {@code as}
281    * @since 1.1
282    */
283   public static <A> Iterable<A> take(final int n, final Iterable<A> as) {
284     if (n < 0) {
285       throw new IllegalArgumentException("Cannot take a negative number of elements");
286     }
287     if (as instanceof List<?>) {
288       final List<A> list = (List<A>) as;
289       return list.subList(0, n < list.size() ? n : list.size());
290     }
291     return new Take<>(as, countingPredicate(n));
292   }
293 
294   /**
295    * Drop the first {@code n} {@code as} and return the rest.
296    *
297    * @param <A> type of {@code as}
298    * @param n number of {@code as} to drop, must greater than or equal to zero
299    * @param as list of values, must not be null and must not contain null
300    * @return remaining {@code as} after dropping the first {@code n}
301    * @since 1.1
302    */
303   public static <A> Iterable<A> drop(final int n, final Iterable<A> as) {
304     if (n < 0) {
305       throw new IllegalArgumentException("Cannot drop a negative number of elements");
306     }
307     if (as instanceof List<?>) {
308       final List<A> list = (List<A>) as;
309       if (n > (list.size() - 1)) {
310         return emptyIterable();
311       }
312       return list.subList(n, list.size());
313     }
314     return new Drop<>(as, countingPredicate(n));
315   }
316 
317   /**
318    * Drop elements of {@code as} until an element returns false for
319    * {@literal p#test}
320    *
321    * @param as iterable to remove the first elements of {@code as}, must not be
322    * null
323    * @param p predicate used to test which elements to drop from the iterable,
324    * must not be null
325    * @param <A> type of {@code as}
326    * @return remaining elements of {@code as} after removing the starting
327    * elements that for which {@code p#test} returns true
328    * @since 3.0
329    * @see #drop(int, Iterable) to remove the first n elements
330    */
331   public static <A> Iterable<A> dropWhile(final Iterable<A> as, final Predicate<A> p) {
332     return new Drop<>(as, p);
333   }
334 
335   /**
336    * Return a new iterable containing only the first elements of {@code as} for
337    * which {@code p#test} returns true.
338    *
339    * @param as iterable to source the first elements of {@code as}, must not be
340    * null
341    * @param p predicate used to test which elements to include in the new
342    * iterable, must not be null
343    * @param <A> type of {@code as}
344    * @return a new iterable containing elements of {@code as} starting from the
345    * first element of {@code as} until {@code p#test} returns false
346    * @since 3.0
347    * @see #take(int, Iterable) to take only the first n elements
348    */
349   public static <A> Iterable<A> takeWhile(final Iterable<A> as, final Predicate<A> p) {
350     return new Take<>(as, p);
351   }
352 
353   /**
354    * Zips two iterables into a single iterable that produces {@link Pair pairs}.
355    * See unzip(Iterable) for the opposite operation
356    *
357    * @param <A> LHS type
358    * @param <B> RHS type
359    * @param as left values
360    * @param bs right values
361    * @return an {@link Iterable iterable} of pairs, only as long as the shortest
362    * input iterable.
363    * @since 1.2
364    */
365   public static <A, B> Iterable<Pair<A, B>> zip(final Iterable<A> as, final Iterable<B> bs) {
366     return zipWith(Pair.<A, B> pairs()).apply(as, bs);
367   }
368 
369   /**
370    * Takes a two-arg function that returns a third type and reurn a new function
371    * that takes iterables of the two input types and combines them into a new
372    * iterable.
373    *
374    * @param <A> LHS type
375    * @param <B> RHS type
376    * @param <C> result type
377    * @param f combiner function, must not be null
378    * @return an Function that takes two iterables and zips them using the
379    * supplied function. The input iterables must not be null and must not
380    * contain null
381    * @since 1.2
382    */
383   public static <A, B, C> BiFunction<Iterable<A>, Iterable<B>, Iterable<C>> zipWith(final BiFunction<A, B, C> f) {
384     return (as, bs) -> new Zipper<>(as, bs, f);
385   }
386 
387   /**
388    * Takes an Iterable, and returns an Iterable of a Pair of the original
389    * element and its index starting at zero.
390    *
391    * @param <A> the type
392    * @param as the original iterable
393    * @return the decorated iterable that generates pairs.
394    * @since 1.2
395    */
396   public static <A> Iterable<Pair<A, Integer>> zipWithIndex(final Iterable<A> as) {
397     return zip(as, rangeTo(0, Integer.MAX_VALUE));
398   }
399 
400   /**
401    * Unzips an iterable of {@link Pair pairs} into a {@link Pair pair} of
402    * iterables.
403    *
404    * @param <A> LHS type
405    * @param <B> RHS type
406    * @param pairs the values
407    * @return a {@link Pair pair} of {@link Iterable iterable} of the same length
408    * as the input iterable.
409    * @since 1.2
410    */
411   public static <A, B> Pair<Iterable<A>, Iterable<B>> unzip(Iterable<Pair<A, B>> pairs) {
412     return pair(map(pairs, leftValue()), map(pairs, rightValue()));
413   }
414 
415   /**
416    * Creates a sequence of {@link Integer integers} from start up to but not
417    * including end.
418    *
419    * @param start from (inclusive)
420    * @param end to (exclusive)
421    * @return a sequence of {@link Integer integers}
422    * @since 1.2
423    */
424   public static Iterable<Integer> rangeUntil(final int start, final int end) {
425     return rangeUntil(start, end, (start > end) ? -1 : 1);
426   }
427 
428   /**
429    * Creates a sequence of {@link Integer integers} from start up to but not
430    * including end with the the supplied step between them.
431    *
432    * @param start from (inclusive)
433    * @param end to (exclusive)
434    * @param step size to step – must not be zero, must be positive if end is
435    * greater than start, neagtive otherwise
436    * @return a sequence of {@link Integer integers}
437    * @since 1.2
438    */
439   public static Iterable<Integer> rangeUntil(final int start, final int end, final int step) {
440     if (step == 0) {
441       throw new IllegalArgumentException("Step must not be zero");
442     }
443     return rangeTo(start, end - (Math.abs(step) / step), step);
444   }
445 
446   /**
447    * Creates a sequence of {@link Integer integers} from start up to and
448    * including end.
449    *
450    * @param start from (inclusive)
451    * @param end to (inclusive)
452    * @return a sequence of {@link Integer integers}
453    * @since 1.2
454    */
455   public static Iterable<Integer> rangeTo(final int start, final int end) {
456     return rangeTo(start, end, (start > end) ? -1 : 1);
457   }
458 
459   /**
460    * Creates a sequence of {@link Integer integers} from start up to and
461    * including end with the the supplied step between them.
462    *
463    * @param start from (inclusive), must be greater than zero and less than end
464    * @param end to (inclusive)
465    * @param step size to step – must not be zero, must be positive if end is
466    * greater than start, neagtive otherwise
467    * @return a sequence of {@link Integer integers}
468    * @since 1.2
469    */
470   public static Iterable<Integer> rangeTo(final int start, final int end, final int step) {
471     if (step == 0) {
472       throw new IllegalArgumentException("Step must not be zero");
473     }
474     if (step > 0) {
475       if (start > end) {
476         throw new IllegalArgumentException(String.format("Start %s must not be greater than end %s with step %s", start, end, step));
477       }
478     } else {
479       if (start < end) {
480         throw new IllegalArgumentException(String.format("Start %s must not be less than end %s with step %s", start, end, step));
481       }
482     }
483 
484     return () -> new Iterators.Unmodifiable<Integer>() {
485       private int i = start;
486 
487       @Override public boolean hasNext() {
488         return step > 0 ? i <= end : i >= end;
489       }
490 
491       @Override public Integer next() {
492         try {
493           return i;
494         } finally {
495           i += step;
496         }
497       }
498     };
499   }
500 
501   static abstract class IterableToString<A> implements Iterable<A> {
502     @Override public final String toString() {
503       return makeString(this, "[", ", ", "]");
504     }
505   }
506 
507   /**
508    * Iterable that only shows a small range of the original Iterable.
509    */
510   static final class Take<A> extends IterableToString<A> {
511     private final Iterable<A> as;
512     private final Predicate<A> p;
513 
514     private Take(final Iterable<A> as, final Predicate<A> p) {
515       this.p = requireNonNull(p);
516       this.as = requireNonNull(as);
517     }
518 
519     @Override public Iterator<A> iterator() {
520       return new Iter<>(as.iterator(), p);
521     }
522 
523     static final class Iter<A> extends Iterators.Abstract<A> {
524       private final Iterator<A> ias;
525       private final Predicate<A> p;
526 
527       Iter(final Iterator<A> ias, final Predicate<A> p) {
528         this.ias = ias;
529         this.p = p;
530       }
531 
532       @Override protected A computeNext() {
533         if (ias.hasNext()) {
534           final A a = ias.next();
535           return p.test(a) ? a : endOfData();
536         }
537         return endOfData();
538       }
539     }
540   }
541 
542   /**
543    * Iterable that only shows a small range of the original Iterable.
544    */
545   static final class Drop<A> extends IterableToString<A> {
546     private final Iterable<A> as;
547     private final Predicate<A> p;
548 
549     private Drop(final Iterable<A> as, final Predicate<A> p) {
550       this.p = requireNonNull(p);
551       this.as = requireNonNull(as);
552     }
553 
554     @Override public Iterator<A> iterator() {
555       return new Iter<>(as.iterator(), p);
556     }
557 
558     static final class Iter<A> extends Iterators.Abstract<A> {
559       private final Iterators.Peeking<A> as;
560 
561       Iter(final Iterator<A> as, final Predicate<A> p) {
562         this.as = peekingIterator(as);
563         while (this.as.hasNext() && p.test(this.as.peek())) {
564           this.as.next();
565         }
566       }
567 
568       @Override protected A computeNext() {
569         return as.hasNext() ? as.next() : endOfData();
570       }
571     }
572   }
573 
574   /**
575    * CollectingIterable, filters and transforms in one.
576    */
577   static class CollectingIterable<A, B> extends IterableToString<B> {
578     private final Iterable<? extends A> delegate;
579     private final Function<? super A, Option<B>> partial;
580 
581     CollectingIterable(final Iterable<? extends A> delegate, final Function<? super A, Option<B>> partial) {
582       this.delegate = requireNonNull(delegate);
583       this.partial = requireNonNull(partial);
584     }
585 
586     @Override public Iterator<B> iterator() {
587       return new Iter();
588     }
589 
590     final class Iter extends Iterators.Abstract<B> {
591       private final Iterator<? extends A> it = delegate.iterator();
592 
593       @Override protected B computeNext() {
594         while (it.hasNext()) {
595           final Option<B> result = partial.apply(it.next());
596           if (result.isDefined())
597             return result.get();
598         }
599         return endOfData();
600       }
601     }
602   }
603 
604   /**
605    * Iterable that combines two iterables using a combiner function.
606    */
607   static class Zipper<A, B, C> extends IterableToString<C> {
608     private final Iterable<A> as;
609     private final Iterable<B> bs;
610     private final BiFunction<A, B, C> f;
611 
612     Zipper(final Iterable<A> as, final Iterable<B> bs, final BiFunction<A, B, C> f) {
613       this.as = requireNonNull(as, "as must not be null.");
614       this.bs = requireNonNull(bs, "bs must not be null.");
615       this.f = requireNonNull(f, "f must not be null.");
616     }
617 
618     @Override public Iterator<C> iterator() {
619       return new Iter();
620     }
621 
622     class Iter implements Iterator<C> {
623       private final Iterator<A> a = requireNonNull(as.iterator(), "as iterator must not be null.");
624       private final Iterator<B> b = requireNonNull(bs.iterator(), "bs iterator must not be null.");
625 
626       @Override public boolean hasNext() {
627         return a.hasNext() && b.hasNext();
628       }
629 
630       @Override public C next() {
631         return f.apply(a.next(), b.next());
632       }
633 
634       @Override public void remove() {
635         throw new UnsupportedOperationException();
636       }
637     }
638   }
639 
640   /**
641    * Intersperse an element between all the elements in an iterable.
642    *
643    * @param <A> the type of the elements.
644    * @param as the source iterable.
645    * @param a the element to intersperse between the source elements.
646    * @return a new Iterable that intersperses the element between the source.
647    * @since 2.3
648    */
649   public static <A> Iterable<A> intersperse(final Iterable<? extends A> as, final A a) {
650     return intersperse(as, ofInstance(a));
651   }
652 
653   /**
654    * Intersperse an element between all the elements in an iterable.
655    *
656    * @param <A> the type of the elements.
657    * @param as the source iterable.
658    * @param a the supplier of elements to intersperse between the source
659    * elements.
660    * @return a new Iterable that intersperses the element between the source.
661    * @since 2.3
662    */
663   public static <A> Iterable<A> intersperse(final Iterable<? extends A> as, final Supplier<A> a) {
664     return new Intersperse<>(as, a);
665   }
666 
667   static final class Intersperse<A> implements Iterable<A> {
668     private final Iterable<? extends A> as;
669     private final Supplier<A> a;
670 
671     Intersperse(final Iterable<? extends A> as, final Supplier<A> a) {
672       this.as = as;
673       this.a = a;
674     }
675 
676     @Override public Iterator<A> iterator() {
677       return new Iterators.Abstract<A>() {
678         private final Iterator<? extends A> it = as.iterator();
679         private boolean inter = false;
680 
681         @Override protected A computeNext() {
682           if (!it.hasNext()) {
683             return endOfData();
684           }
685           try {
686             return inter ? a.get() : it.next();
687           } finally {
688             inter = !inter;
689           }
690         }
691       };
692     }
693   }
694 
695   /**
696    * Return the size of an iterable. In most cases this function is required to
697    * walk the entire iterable to determine the result. Consider this an O(n)
698    * complexity function.
699    *
700    * @param as iterable to compute the size of
701    * @param <A> element type
702    * @return number of elements in the iterable
703    * @since 3.0
704    */
705   public static <A> int size(final Iterable<A> as) {
706     if (as instanceof Collection) {
707       return ((Collection<?>) as).size();
708     } else {
709       final Iterator<A> iterator = as.iterator();
710       int count = 0;
711       while (iterator.hasNext()) {
712         iterator.next();
713         count++;
714       }
715       return count;
716     }
717   }
718 
719   /**
720    * Transform an interable by mapping a function across each of its elements
721    *
722    * @param as the source iterable
723    * @param f function to apply to all the elements of as
724    * @param <A> original iterable type
725    * @param <B> output iterable type
726    * @return new iterable containing the transformed values produced by f#apply
727    * @since 3.0
728    * @deprecated function provided to make migration easier prefer to use #map
729    * where possible
730    */
731   @Deprecated public static <A, B> Iterable<B> transform(final Iterable<A> as, final Function<? super A, ? extends B> f) {
732     return map(as, f);
733   }
734 
735   /**
736    * Apply the input function to each of the elements of the input iterable
737    * returning a new iterable
738    *
739    * @param as the source iterable
740    * @param f function to apply to all the elements of as
741    * @param <A> original iterable type
742    * @param <B> output iterable type
743    * @return new iterable containing values produced by f#apply called on each
744    * element
745    * @since 3.0
746    */
747   public static <A, B> Iterable<B> map(final Iterable<A> as, final Function<? super A, ? extends B> f) {
748     return new Mapped<>(as, f);
749   }
750 
751   static final class Mapped<A, B> implements Iterable<B> {
752     private final Iterable<? extends A> as;
753     private final Function<? super A, ? extends B> f;
754 
755     Mapped(final Iterable<? extends A> as, final Function<? super A, ? extends B> f) {
756       this.as = as;
757       this.f = f;
758     }
759 
760     @Override public Iterator<B> iterator() {
761       return new Iterators.Abstract<B>() {
762         private final Iterator<? extends A> it = as.iterator();
763 
764         @Override protected B computeNext() {
765           if (!it.hasNext()) {
766             return endOfData();
767           }
768           return f.apply(it.next());
769         }
770       };
771     }
772   }
773 
774   /**
775    * Remove elements from the input iterable for which the predicate returns
776    * false
777    *
778    * @param as original iterable
779    * @param p predicate to filter by
780    * @param <A> element type
781    * @return new iterable containing only those elements for which p#test
782    * returns true
783    * @since 3.0
784    */
785   public static <A> Iterable<A> filter(final Iterable<A> as, final Predicate<? super A> p) {
786     return new Filter<>(as, p);
787   }
788 
789   static final class Filter<A> implements Iterable<A> {
790     private final Iterable<? extends A> as;
791     private final Predicate<? super A> p;
792 
793     Filter(final Iterable<? extends A> as, final Predicate<? super A> p) {
794       this.as = as;
795       this.p = p;
796     }
797 
798     @Override public Iterator<A> iterator() {
799       return new Iterators.Abstract<A>() {
800         private final Iterator<? extends A> it = as.iterator();
801 
802         @Override protected A computeNext() {
803           if (!it.hasNext()) {
804             return endOfData();
805           }
806           while (it.hasNext()) {
807             final A a = it.next();
808             if (p.test(a)) {
809               return a;
810             }
811           }
812           return endOfData();
813         }
814       };
815     }
816   }
817 
818   /**
819    * Join {@literal Iterable<Iterable<A>>} down to {@literal Iterable<A>}. The
820    * resulting iterable will exhaust the first input iterable in order before
821    * returning values from the second. Input iterables must not be null and must
822    * not contain null.
823    *
824    * @param ias one or more iterable to merge into the final iterable result,
825    * must not be null and must not return null
826    * @param <A> element type
827    * @return single level iterable with all the elements of the original
828    * iterables
829    * @since 3.0
830    */
831   public static <A> Iterable<A> join(final Iterable<? extends Iterable<? extends A>> ias) {
832     return new Join<>(ias);
833   }
834 
835   static final class Join<A> extends IterableToString<A> {
836     private final Iterable<? extends Iterable<? extends A>> ias;
837 
838     public Join(final Iterable<? extends Iterable<? extends A>> ias) {
839       this.ias = ias;
840     }
841 
842     @Override public Iterator<A> iterator() {
843       return new Iter<>(ias);
844     }
845 
846     static class Iter<A> extends Iterators.Abstract<A> {
847       final Queue<Iterator<? extends A>> qas = new LinkedList<>();
848 
849       public Iter(final Iterable<? extends Iterable<? extends A>> ias) {
850         for (final Iterable<? extends A> a : ias) {
851           qas.add(requireNonNull(a.iterator()));
852         }
853       }
854 
855       @Override protected A computeNext() {
856         while (!qas.isEmpty() && !qas.peek().hasNext()) {
857           qas.remove();
858         }
859         if (qas.isEmpty()) {
860           return endOfData();
861         }
862         return qas.peek().next();
863       }
864     }
865   }
866 
867   /**
868    * Concatenate a series of iterables into a single iterable. Returns an empty
869    * iterable if no iterables are supplied. Input iterables must not be null and
870    * must not contain null.
871    *
872    * @param as any number of iterables containing A
873    * @param <A> super type of contained by all input iterables
874    * @return new iterable containing all the elements of the input iterables
875    * @since 3.0
876    */
877   @SafeVarargs public static <A> Iterable<A> concat(final Iterable<? extends A>... as) {
878     return as.length > 0 ? join(Arrays.asList(as)) : emptyIterable();
879   }
880 
881   /**
882    * Check if the iterable contains any elements that match the predicate.
883    *
884    * @param as iterable to compare for matching elements
885    * @param p predicate to test for matching elements
886    * @param <A> type of elements inside the input iterable
887    * @return true if any element in the iterable returns true for the input
888    * predicate otherwise false. False for an empty iterable.
889    * @since 3.0
890    */
891   public static <A> boolean any(final Iterable<? extends A> as, final Predicate<? super A> p) {
892     return !isEmpty().test(filter(as, p));
893   }
894 
895   /**
896    * Check if all elements in the input iterable match the input predicate
897    *
898    * @param as iterable to compare for matching elements
899    * @param p predicate to test for matching elements
900    * @param <A> type of elements inside the input iterable
901    * @return true if all elements in the iterable return true for the input
902    * predicate otherwise false. True for an empty iterable.
903    * @since 3.0
904    */
905   public static <A> boolean all(final Iterable<? extends A> as, final Predicate<? super A> p) {
906     return isEmpty().test(filter(as, p.negate()));
907   }
908 
909   /**
910    * Returns an infinite Iterable constructed by applying the given iteration
911    * function starting at the given value.
912    *
913    * @param <A> type of the elements
914    * @param f The iteration function, must not return null
915    * @param start The value to begin iterating from.
916    * @return An infinite Iterable of repeated applications of {@code f} to
917    * {@code start}.
918    * @since 2.4
919    */
920   public static <A> Iterable<A> iterate(final Function<? super A, ? extends A> f, final A start) {
921     return new IteratingIterable<>(f, start);
922   }
923 
924   /**
925    * Infinite iterable that repeatedly applies {@code f} to {@code start}
926    */
927   static final class IteratingIterable<A> implements Iterable<A> {
928     private final Function<? super A, ? extends A> f;
929     private final A start;
930 
931     private IteratingIterable(final Function<? super A, ? extends A> f, final A start) {
932       this.f = requireNonNull(f, "f");
933       this.start = start;
934     }
935 
936     @Override public Iterator<A> iterator() {
937       return new Iter<>(f, start);
938     }
939 
940     static final class Iter<A> extends Iterators.Unmodifiable<A> {
941       private final Function<? super A, ? extends A> f;
942       private A current;
943 
944       Iter(final Function<? super A, ? extends A> f, final A start) {
945         this.f = f;
946         this.current = start;
947       }
948 
949       @Override public boolean hasNext() {
950         return true;
951       }
952 
953       @Override public A next() {
954         final A value = current;
955         current = f.apply(current);
956         return value;
957       }
958     }
959   }
960 
961   /**
962    * Builds an Iterable from a seed value until {@code f} returns {@code none()}
963    * .
964    *
965    * @param <A> type of the returned elements.
966    * @param <B> type of the elements for which {@code f} is applied.
967    * @param f The function that returns some(pair(a, b)), in which case
968    * {@code a} is the next element of the resulting Iterable and {@code b} is
969    * used as the input value for the next call of {@code f}, or {@code none()}
970    * if it is done producing the elements. f must not be null and must not
971    * return a pair containing null.
972    * @param seed The start value to begin the unfold.
973    * @return An Iterable that is a result of unfolding.
974    * @since 2.4
975    */
976   public static <A, B> Iterable<A> unfold(final Function<? super B, Option<Pair<A, B>>> f, final B seed) {
977     return new UnfoldingIterable<>(f, seed);
978   }
979 
980   /**
981    * Iterable that repeatedly applies {@code f} until it returns {@code none()}
982    */
983   static final class UnfoldingIterable<A, B> extends IterableToString<A> {
984     private final Function<? super B, Option<Pair<A, B>>> f;
985     private final B seed;
986 
987     private UnfoldingIterable(final Function<? super B, Option<Pair<A, B>>> f, final B seed) {
988       this.f = requireNonNull(f, "f");
989       this.seed = seed;
990     }
991 
992     @Override public Iterator<A> iterator() {
993       return new Iter<>(f, seed);
994     }
995 
996     static final class Iter<A, B> extends Iterators.Abstract<A> {
997       private final Function<? super B, Option<Pair<A, B>>> f;
998       private B current;
999 
1000       Iter(final Function<? super B, Option<Pair<A, B>>> f, final B seed) {
1001         this.f = f;
1002         this.current = seed;
1003       }
1004 
1005       @Override protected A computeNext() {
1006         final Option<Pair<A, B>> option = f.apply(current);
1007         if (option.isDefined()) {
1008           final Pair<A, B> pair = option.get();
1009           current = pair.right();
1010           return pair.left();
1011         } else {
1012           return endOfData();
1013         }
1014       }
1015     }
1016   }
1017 
1018   /**
1019    * Merge a number of already sorted collections of elements into a single
1020    * collection of elements, using the elements natural ordering.
1021    *
1022    * @param <A> collection type
1023    * @param xss collection of already sorted collections, must not be null and
1024    * must not return null
1025    * @return {@code xss} merged in a sorted order
1026    * @since 1.1
1027    */
1028   public static <A extends Comparable<A>> Iterable<A> mergeSorted(final Iterable<? extends Iterable<A>> xss) {
1029     return mergeSorted(xss, Comparator.<A> naturalOrder());
1030   }
1031 
1032   /**
1033    * Merge a number of already sorted collections of elements into a single
1034    * collection of elements.
1035    *
1036    * @param <A> type of the elements
1037    * @param xss already sorted collection of collections, must not be null and
1038    * must not return null
1039    * @param ordering ordering to use when comparing elements, must not be null
1040    * @return {@code xss} merged in a sorted order
1041    * @since 1.1
1042    */
1043   public static <A> Iterable<A> mergeSorted(final Iterable<? extends Iterable<A>> xss, final Comparator<A> ordering) {
1044     return new MergeSortedIterable<>(xss, ordering);
1045   }
1046 
1047   /**
1048    * Add all the elements of the iterable to the collection
1049    *
1050    * @param collectionToModify collection to add elements to
1051    * @param elementsToAdd source of addtional elements
1052    * @param <A> element type
1053    * @return true if the collectionToModify was changed
1054    * @since 3.0
1055    */
1056   @SuppressWarnings("unchecked") public static <A> boolean addAll(final Collection<A> collectionToModify, final Iterable<? extends A> elementsToAdd) {
1057     if (elementsToAdd instanceof Collection) {
1058       return collectionToModify.addAll((Collection<? extends A>) elementsToAdd);
1059     }
1060     return Iterators.addAll(collectionToModify, requireNonNull(elementsToAdd).iterator());
1061   }
1062 
1063   /**
1064    * Merges multiple sorted Iterables into one, sorted iterable.
1065    */
1066   static final class MergeSortedIterable<A> extends IterableToString<A> {
1067     private final Iterable<? extends Iterable<A>> xss;
1068     private final Comparator<A> comparator;
1069 
1070     MergeSortedIterable(final Iterable<? extends Iterable<A>> xss, final Comparator<A> comparator) {
1071       this.xss = requireNonNull(xss, "xss");
1072       this.comparator = requireNonNull(comparator, "comparator");
1073     }
1074 
1075     @Override public Iterator<A> iterator() {
1076       return new Iter<>(xss, comparator);
1077     }
1078 
1079     private static final class Iter<A> extends Iterators.Abstract<A> {
1080       private final TreeSet<Iterators.Peeking<A>> xss;
1081 
1082       private Iter(final Iterable<? extends Iterable<A>> xss, final Comparator<A> c) {
1083         this.xss = new TreeSet<>(peekingIteratorComparator(c));
1084         addAll(this.xss, map(filter(xss, isEmpty().negate()), i -> peekingIterator(i.iterator())));
1085       }
1086 
1087       @Override protected A computeNext() {
1088         final Option<Iterators.Peeking<A>> currFirstOption = first(xss);
1089         if (!currFirstOption.isDefined()) {
1090           return endOfData();
1091         }
1092         final Iterators.Peeking<A> currFirst = currFirstOption.get();
1093 
1094         // We remove the iterator from the set first, before we mutate it,
1095         // otherwise we wouldn't be able to
1096         // properly find it to remove it. Mutation sucks.
1097         xss.remove(currFirst);
1098 
1099         final A next = currFirst.next();
1100         if (currFirst.hasNext()) {
1101           xss.add(currFirst);
1102         }
1103         return next;
1104       }
1105 
1106       private Comparator<? super Iterators.Peeking<A>> peekingIteratorComparator(final Comparator<A> comparator) {
1107         return (lhs, rhs) -> (lhs == rhs) ? 0 : comparator.compare(lhs.peek(), rhs.peek());
1108       }
1109     }
1110   }
1111 
1112   /**
1113    * Return an infinite iterable that cycles through the input values in order
1114    * in a loop. If no elements are provided returns an empty iterable. Does not
1115    * support element removal via Iterator#remove.
1116    *
1117    * @param as input values to cycle through
1118    * @param <A> returned elements
1119    * @return an infinite iterable containing the original elements
1120    * @since 3.0
1121    */
1122   @SafeVarargs public static <A> Iterable<A> cycle(final A... as) {
1123     if (as.length > 0) {
1124       return new Cycle<>(Arrays.asList(as));
1125     } else {
1126       return emptyIterable();
1127     }
1128   }
1129 
1130   /**
1131    * Return an infinite iterable that cycles through the input values in order
1132    * in a loop. If no elements are provided returns an empty iterable. Does not
1133    * support element removal via Iterator#remove.
1134    *
1135    * @param as input values to cycle through must not be null
1136    * @param <A> returned elements
1137    * @return an infinite iterable containing the original elements
1138    * @since 3.0
1139    */
1140   public static <A> Iterable<A> cycle(final Iterable<? extends A> as) {
1141     return new Cycle<>(as);
1142   }
1143 
1144   static final class Cycle<A> implements Iterable<A> {
1145     final Iterable<? extends A> as;
1146 
1147     Cycle(final Iterable<? extends A> as) {
1148       this.as = requireNonNull(as);
1149     }
1150 
1151     @Override public Iterator<A> iterator() {
1152       return new Iter<>(as);
1153     }
1154 
1155     static final class Iter<A> extends Iterators.Abstract<A> {
1156       Iterable<? extends A> as;
1157       Iterator<? extends A> ias;
1158 
1159       Iter(final Iterable<? extends A> as) {
1160         this.as = as;
1161         this.ias = as.iterator();
1162       }
1163 
1164       @Override protected A computeNext() {
1165         if (!ias.hasNext() && !(ias = as.iterator()).hasNext()) {
1166           return endOfData();
1167         }
1168         return ias.next();
1169       }
1170     }
1171 
1172     @Override public String toString() {
1173       return makeString(as, "[", ", ", "...]", 100);
1174     }
1175   }
1176 
1177   /**
1178    * Pretty print an Iterable.
1179    *
1180    * Printing following this pattern:
1181    * {@literal <start><element><sep><element><end>} If the iterable would result
1182    * in a String with length more than maxLength printing follows this pattern:
1183    * {@literal <start><element><sep><element>...<end>}
1184    *
1185    * @param as the iterable to print must not be null
1186    * @param start prefix to start the printing with
1187    * @param sep separator to use between each element
1188    * @param end suffic to end the printing with
1189    * @param maxLength limit the length of the resulting string
1190    * @param <A> type of the elements in the iterable
1191    * @return a pretty printed copy of the input iterable
1192    * @since 3.0
1193    */
1194   public static <A> String makeString(final Iterable<? extends A> as, final String start, final String sep, final String end, final int maxLength) {
1195     final StringBuilder b = new StringBuilder();
1196     b.append(start);
1197     final Iterator<? extends A> ias = requireNonNull(as).iterator();
1198 
1199     if (ias.hasNext()) {
1200       b.append(String.valueOf(ias.next()));
1201     }
1202     while (ias.hasNext()) {
1203       if (b.length() >= maxLength) {
1204         break;
1205       }
1206 
1207       b.append(sep);
1208       final String value = String.valueOf(ias.next());
1209       b.append(value);
1210     }
1211     if (ias.hasNext()) {
1212       b.append("...");
1213     }
1214     b.append(end);
1215     return b.toString();
1216   }
1217 
1218   /**
1219    * Pretty print an Iterable.
1220    *
1221    * Printing following this pattern:
1222    * {@literal <start><element><sep><element><end>} If the iterable would result
1223    * in a String with length more than 100 characters printing follows this
1224    * pattern: {@literal <start><element><sep><element>...<end>}
1225    *
1226    * @param as the iterable to print must not be null
1227    * @param start prefix to start the printing with
1228    * @param sep separator to use between each element
1229    * @param end suffic to end the printing with
1230    * @param <A> type of the elements in the iterable
1231    * @return a pretty printed copy of the input iterable
1232    * @see #makeString(Iterable, String, String, String, int) pretty print
1233    * iterable with a custom length
1234    * @since 3.0
1235    */
1236   public static <A> String makeString(final Iterable<? extends A> as, final String start, final String sep, final String end) {
1237     return makeString(as, start, sep, end, 100);
1238   }
1239 
1240   /**
1241    * Makes a lazy copy of {@code xs}.
1242    *
1243    * @param <A> type of elements in {@code xs}
1244    * @param xs {@code Iterable} to be memoized
1245    * @return lazy copy of {@code as}
1246    * @since 1.1
1247    */
1248   public static <A> Iterable<A> memoize(final Iterable<A> xs) {
1249     return new Memoizer<>(xs);
1250   }
1251 
1252   /**
1253    * Memoizing iterable, maintains a lazily computed linked list of nodes.
1254    */
1255   static final class Memoizer<A> extends IterableToString<A> {
1256     private final Node<A> head;
1257 
1258     Memoizer(final Iterable<A> delegate) {
1259       head = nextNode(delegate.iterator());
1260     }
1261 
1262     @Override public Iterator<A> iterator() {
1263       return new Iter<>(head);
1264     }
1265 
1266     private static <A> Node<A> nextNode(final Iterator<A> delegate) {
1267       return delegate.hasNext() ? new Lazy<>(delegate) : new End<>();
1268     }
1269 
1270     /**
1271      * Linked list node.
1272      */
1273     interface Node<A> {
1274       boolean isEnd();
1275 
1276       A value();
1277 
1278       /**
1279        * Get the next Node.
1280        *
1281        * @return a new Node
1282        * @throws java.util.NoSuchElementException if this is terminal
1283        */
1284       Node<A> next() throws NoSuchElementException;
1285     }
1286 
1287     /**
1288      * Lazily computes the next node. Has a value so is not an end.
1289      */
1290     static class Lazy<A> extends LazyReference<Node<A>> implements Node<A> {
1291       private final Iterator<A> delegate;
1292       private final A value;
1293 
1294       Lazy(final Iterator<A> delegate) {
1295         this.delegate = delegate;
1296         this.value = delegate.next();
1297       }
1298 
1299       @Override protected Node<A> create() throws Exception {
1300         return nextNode(delegate);
1301       }
1302 
1303       @Override public Node<A> next() throws NoSuchElementException {
1304         return get();
1305       }
1306 
1307       @Override public boolean isEnd() {
1308         return false;
1309       }
1310 
1311       @Override public A value() {
1312         return value;
1313       }
1314     }
1315 
1316     static class End<A> implements Node<A> {
1317       @Override public boolean isEnd() {
1318         return true;
1319       }
1320 
1321       // /CLOVER:OFF
1322       @Override public Node<A> next() {
1323         throw new NoSuchElementException();
1324       }
1325 
1326       @Override public A value() {
1327         throw new NoSuchElementException();
1328       }
1329       // /CLOVER:ON
1330     }
1331 
1332     static class Iter<A> extends Iterators.Abstract<A> {
1333       Node<A> node;
1334 
1335       Iter(final Node<A> node) {
1336         this.node = node;
1337       }
1338 
1339       @Override protected A computeNext() {
1340         if (node.isEnd()) {
1341           return endOfData();
1342         }
1343         try {
1344           return node.value();
1345         } finally {
1346           node = node.next();
1347         }
1348       }
1349     }
1350   }
1351 
1352   /**
1353    * Class supports the implementation of {@link Iterables#memoize(Iterable)}
1354    * and is not intended for general use.
1355    *
1356    * Lazily loaded reference that is not constructed until required. This class
1357    * is used to maintain a reference to an object that is expensive to create
1358    * and must be constructed once and once only. This reference behaves as
1359    * though the <code>final</code> keyword has been used (you cannot reset it
1360    * once it has been constructed). Object creation is guaranteed to be
1361    * thread-safe and the first thread that calls {@link #get()} will be the one
1362    * that creates it.
1363    * <p>
1364    * Usage: clients need to implement the {@link #create()} method to return the
1365    * object this reference will hold.
1366    * <p>
1367    * For instance:
1368    * <p>
1369    *
1370    * <pre>
1371    * final LazyReference&lt;MyObject&gt; ref = new LazyReference() {
1372    *   protected MyObject create() throws Exception {
1373    *     // Do expensive object construction here
1374    *     return new MyObject();
1375    *   }
1376    * };
1377    * </pre>
1378    *
1379    * Then call {@link #get()} to get a reference to the referenced object:
1380    *
1381    * <pre>
1382    * MyObject myLazyLoadedObject = ref.get()
1383    * </pre>
1384    *
1385    * NOTE: Interruption policy is that if you want to be cancellable while
1386    * waiting for another thread to create the value, instead of calling
1387    * {@link #get()} call {@link #getInterruptibly()}. However, If your
1388    * {@link #create()} method is interrupted and throws an
1389    * {@link InterruptedException}, it is treated as an application exception and
1390    * will be the causal exception inside the runtime
1391    * {@link InitializationException} that {@link #get()} or
1392    * {@link #getInterruptibly()} throws and your {@link #create()} will not be
1393    * called again.
1394    * <p>
1395    * This class is NOT {@link Serializable}.
1396    * <p>
1397    * Implementation note. This class extends {@link WeakReference} as
1398    * {@link Reference} does not have a public constructor. WeakReference is
1399    * preferable as it does not have any members and therefore doesn't increase
1400    * the memory footprint. As we never pass a referent through to the
1401    * super-class and override {@link #get()}, the garbage collection semantics
1402    * of WeakReference are irrelevant. The referenced object will not become
1403    * eligible for GC unless the object holding the reference to this object is
1404    * collectible.
1405    *
1406    * @param <T> the type of the contained element.
1407    */
1408   // @ThreadSafe
1409   static abstract class LazyReference<T> extends WeakReference<T> implements Supplier<T> {
1410 
1411     private final Sync sync = new Sync();
1412 
1413     public LazyReference() {
1414       super(null);
1415     }
1416 
1417     /**
1418      * The object factory method, guaranteed to be called once and only once.
1419      *
1420      * @return the object that {@link #get()} and {@link #getInterruptibly()}
1421      * will return.
1422      * @throws Exception if anything goes wrong, rethrown as an
1423      * InitializationException from {@link #get()} and
1424      * {@link #getInterruptibly()}
1425      */
1426     protected abstract T create() throws Exception;
1427 
1428     /**
1429      * Get the lazily loaded reference in a non-cancellable manner. If your
1430      * <code>create()</code> method throws an Exception calls to
1431      * <code>get()</code> will throw an InitializationException which wraps the
1432      * previously thrown exception.
1433      *
1434      * @return the object that {@link #create()} created.
1435      * @throws InitializationException if the {@link #create()} method throws an
1436      * exception. The {@link InitializationException#getCause()} will contain
1437      * the exception thrown by the {@link #create()} method
1438      */
1439     @Override public final T get() {
1440       boolean interrupted = false;
1441       try {
1442         while (true) {
1443           try {
1444             return getInterruptibly();
1445           } catch (final InterruptedException ignore) {
1446             // ignore and try again
1447             interrupted = true;
1448           }
1449         }
1450       } finally {
1451         if (interrupted) {
1452           Thread.currentThread().interrupt();
1453         }
1454       }
1455     }
1456 
1457     /**
1458      * Get the lazily loaded reference in a cancellable manner. If your
1459      * <code>create()</code> method throws an Exception, calls to
1460      * <code>get()</code> will throw a RuntimeException which wraps the
1461      * previously thrown exception.
1462      *
1463      * @return the object that {@link #create()} created.
1464      * @throws InitializationException if the {@link #create()} method throws an
1465      * exception. The {@link InitializationException#getCause()} will contain
1466      * the exception thrown by the {@link #create()} method
1467      * @throws InterruptedException If the calling thread is Interrupted while
1468      * waiting for another thread to create the value (if the creating thread is
1469      * interrupted while blocking on something, the {@link InterruptedException}
1470      * will be thrown as the causal exception of the
1471      * {@link InitializationException} to everybody calling this method).
1472      */
1473     public final T getInterruptibly() throws InterruptedException {
1474       if (!sync.isDone()) {
1475         sync.run();
1476       }
1477 
1478       try {
1479         return sync.get();
1480       } catch (final ExecutionException e) {
1481         throw new InitializationException(e);
1482       }
1483     }
1484 
1485     /**
1486      * Has the {@link #create()} reference been initialized.
1487      *
1488      * @return true if the task is complete
1489      */
1490     public final boolean isInitialized() {
1491       return sync.isDone();
1492     }
1493 
1494     /**
1495      * Cancel the initializing operation if it has not already run. Will try and
1496      * interrupt if it is currently running.
1497      */
1498     public final void cancel() {
1499       sync.cancel(true);
1500     }
1501 
1502     /**
1503      * If the factory {@link LazyReference#create()} method threw an exception,
1504      * this wraps it.
1505      */
1506     public static class InitializationException extends RuntimeException {
1507       private static final long serialVersionUID = 3638376010285456759L;
1508 
1509       InitializationException(final ExecutionException e) {
1510         super((e.getCause() != null) ? e.getCause() : e);
1511       }
1512     }
1513 
1514     static final class State {
1515       static final int INIT = 0;
1516       static final int RUNNING = 1;
1517       static final int RAN = 2;
1518       static final int CANCELLED = 4;
1519     }
1520 
1521     /**
1522      * Synchronization control for LazyReference. Note that this must be a
1523      * non-static inner class in order to invoke the protected <tt>create</tt>
1524      * method. Taken from FutureTask AQS implementation and pruned to be as
1525      * compact as possible.
1526      *
1527      * Uses AQS sync state to represent run status.
1528      */
1529     private final class Sync extends AbstractQueuedSynchronizer {
1530 
1531       static final int IGNORED = 0;
1532 
1533       /**
1534        * only here to shut up the compiler warnings, the outer class is NOT
1535        * serializable
1536        */
1537       private static final long serialVersionUID = -1645412544240373524L;
1538 
1539       /** The result to return from get() */
1540       private T result;
1541       /** The exception to throw from get() */
1542       private Throwable exception;
1543 
1544       /**
1545        * The thread running task. When nulled after set/cancel, this indicates
1546        * that the results are accessible. Must be volatile, to ensure visibility
1547        * upon completion.
1548        */
1549       private volatile Thread runner;
1550 
1551       private boolean ranOrCancelled(final int state) {
1552         return (state & (State.RAN | State.CANCELLED)) != State.INIT;
1553       }
1554 
1555       /**
1556        * Implements AQS base acquire to succeed if ran or cancelled
1557        */
1558       @Override protected int tryAcquireShared(final int ignore) {
1559         return isDone() ? 1 : -1;
1560       }
1561 
1562       /**
1563        * Implements AQS base release to always signal after setting final done
1564        * status by nulling runner thread.
1565        */
1566       @Override protected boolean tryReleaseShared(final int ignore) {
1567         runner = null;
1568         return true;
1569       }
1570 
1571       boolean isDone() {
1572         return ranOrCancelled(getState()) && (runner == null);
1573       }
1574 
1575       T get() throws InterruptedException, ExecutionException {
1576         acquireSharedInterruptibly(IGNORED);
1577         if (getState() == State.CANCELLED) {
1578           throw new CancellationException();
1579         }
1580         if (exception != null) {
1581           throw new ExecutionException(exception);
1582         }
1583         return result;
1584       }
1585 
1586       void set(final T v) {
1587         for (;;) {
1588           final int s = getState();
1589           if (s == State.RAN) {
1590             return;
1591           }
1592           if (s == State.CANCELLED) {
1593             // aggressively release to set runner to null,
1594             // in case we are racing with a cancel request
1595             // that will try to interrupt runner
1596             releaseShared(IGNORED);
1597             return;
1598           }
1599           if (compareAndSetState(s, State.RAN)) {
1600             result = v;
1601             releaseShared(IGNORED);
1602             return;
1603           }
1604         }
1605       }
1606 
1607       void setException(final Throwable t) {
1608         for (;;) {
1609           final int s = getState();
1610           if (s == State.RAN) {
1611             return;
1612           }
1613           if (s == State.CANCELLED) {
1614             // aggressively release to set runner to null,
1615             // in case we are racing with a cancel request
1616             // that will try to interrupt runner
1617             releaseShared(0);
1618             return;
1619           }
1620           if (compareAndSetState(s, State.RAN)) {
1621             exception = t;
1622             result = null;
1623             releaseShared(0);
1624             return;
1625           }
1626         }
1627       }
1628 
1629       void cancel(final boolean mayInterruptIfRunning) {
1630         for (;;) {
1631           final int s = getState();
1632           if (ranOrCancelled(s)) {
1633             return;
1634           }
1635           if (compareAndSetState(s, State.CANCELLED)) {
1636             break;
1637           }
1638         }
1639         if (mayInterruptIfRunning) {
1640           final Thread r = runner;
1641           if (r != null) {
1642             r.interrupt();
1643           }
1644         }
1645         releaseShared(IGNORED);
1646       }
1647 
1648       void run() {
1649         if ((getState() != State.INIT) || !compareAndSetState(State.INIT, State.RUNNING)) {
1650           if (runner == Thread.currentThread()) {
1651             throw new IllegalMonitorStateException("Not reentrant!");
1652           }
1653           return;
1654         }
1655         try {
1656           runner = Thread.currentThread();
1657           set(create());
1658         } catch (final Throwable ex) {
1659           setException(ex);
1660         }
1661       }
1662     }
1663   }
1664 }