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 java.io.Serializable;
20  import java.lang.ref.Reference;
21  import java.lang.ref.WeakReference;
22  import java.util.Arrays;
23  import java.util.Collection;
24  import java.util.Comparator;
25  import java.util.Iterator;
26  import java.util.LinkedList;
27  import java.util.List;
28  import java.util.NoSuchElementException;
29  import java.util.Queue;
30  import java.util.TreeSet;
31  import java.util.concurrent.CancellationException;
32  import java.util.concurrent.ExecutionException;
33  import java.util.concurrent.locks.AbstractQueuedSynchronizer;
34  import java.util.function.BiFunction;
35  import java.util.function.Function;
36  import java.util.function.Predicate;
37  import java.util.function.Supplier;
38  import java.util.stream.Collector;
39  import java.util.stream.StreamSupport;
40  
41  import static io.atlassian.fugue.Functions.countingPredicate;
42  import static io.atlassian.fugue.Iterators.emptyIterator;
43  import static io.atlassian.fugue.Iterators.peekingIterator;
44  import static io.atlassian.fugue.Option.none;
45  import static io.atlassian.fugue.Option.some;
46  import static io.atlassian.fugue.Pair.leftValue;
47  import static io.atlassian.fugue.Pair.pair;
48  import static io.atlassian.fugue.Pair.rightValue;
49  import static io.atlassian.fugue.Suppliers.ofInstance;
50  import static java.util.Arrays.asList;
51  import static java.util.Collections.unmodifiableCollection;
52  import static java.util.Objects.requireNonNull;
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, negative 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       private boolean reachedMinOrMax = false;
487 
488       @Override public boolean hasNext() {
489         return (step > 0 ? i <= end : i >= end) && !reachedMinOrMax;
490       }
491 
492       @Override public Integer next() {
493         if (!hasNext()) {
494           throw new NoSuchElementException();
495         }
496         try {
497           return i;
498         } finally {
499           int attempt = i + step;
500           // see Math#addExact(int,int)
501           if (((i ^ attempt) & (step ^ attempt)) < 0) {
502             reachedMinOrMax = true;
503           }
504           i = attempt;
505         }
506       }
507     };
508   }
509 
510   static abstract class IterableToString<A> implements Iterable<A> {
511     @Override public final String toString() {
512       return makeString(this, "[", ", ", "]");
513     }
514   }
515 
516   /**
517    * Iterable that only shows a small range of the original Iterable.
518    */
519   static final class Take<A> extends IterableToString<A> {
520     private final Iterable<A> as;
521     private final Predicate<A> p;
522 
523     private Take(final Iterable<A> as, final Predicate<A> p) {
524       this.p = requireNonNull(p);
525       this.as = requireNonNull(as);
526     }
527 
528     @Override public Iterator<A> iterator() {
529       return new Iter<>(as.iterator(), p);
530     }
531 
532     static final class Iter<A> extends Iterators.Abstract<A> {
533       private final Iterator<A> ias;
534       private final Predicate<A> p;
535 
536       Iter(final Iterator<A> ias, final Predicate<A> p) {
537         this.ias = ias;
538         this.p = p;
539       }
540 
541       @Override protected A computeNext() {
542         if (ias.hasNext()) {
543           final A a = ias.next();
544           return p.test(a) ? a : endOfData();
545         }
546         return endOfData();
547       }
548     }
549   }
550 
551   /**
552    * Iterable that only shows a small range of the original Iterable.
553    */
554   static final class Drop<A> extends IterableToString<A> {
555     private final Iterable<A> as;
556     private final Predicate<A> p;
557 
558     private Drop(final Iterable<A> as, final Predicate<A> p) {
559       this.p = requireNonNull(p);
560       this.as = requireNonNull(as);
561     }
562 
563     @Override public Iterator<A> iterator() {
564       return new Iter<>(as.iterator(), p);
565     }
566 
567     static final class Iter<A> extends Iterators.Abstract<A> {
568       private final Iterators.Peeking<A> as;
569 
570       Iter(final Iterator<A> as, final Predicate<A> p) {
571         this.as = peekingIterator(as);
572         while (this.as.hasNext() && p.test(this.as.peek())) {
573           this.as.next();
574         }
575       }
576 
577       @Override protected A computeNext() {
578         return as.hasNext() ? as.next() : endOfData();
579       }
580     }
581   }
582 
583   /**
584    * CollectingIterable, filters and transforms in one.
585    */
586   static class CollectingIterable<A, B> extends IterableToString<B> {
587     private final Iterable<? extends A> delegate;
588     private final Function<? super A, Option<B>> partial;
589 
590     CollectingIterable(final Iterable<? extends A> delegate, final Function<? super A, Option<B>> partial) {
591       this.delegate = requireNonNull(delegate);
592       this.partial = requireNonNull(partial);
593     }
594 
595     @Override public Iterator<B> iterator() {
596       return new Iter();
597     }
598 
599     final class Iter extends Iterators.Abstract<B> {
600       private final Iterator<? extends A> it = delegate.iterator();
601 
602       @Override protected B computeNext() {
603         while (it.hasNext()) {
604           final Option<B> result = partial.apply(it.next());
605           if (result.isDefined())
606             return result.get();
607         }
608         return endOfData();
609       }
610     }
611   }
612 
613   /**
614    * Iterable that combines two iterables using a combiner function.
615    */
616   static class Zipper<A, B, C> extends IterableToString<C> {
617     private final Iterable<A> as;
618     private final Iterable<B> bs;
619     private final BiFunction<A, B, C> f;
620 
621     Zipper(final Iterable<A> as, final Iterable<B> bs, final BiFunction<A, B, C> f) {
622       this.as = requireNonNull(as, "as must not be null.");
623       this.bs = requireNonNull(bs, "bs must not be null.");
624       this.f = requireNonNull(f, "f must not be null.");
625     }
626 
627     @Override public Iterator<C> iterator() {
628       return new Iter();
629     }
630 
631     class Iter implements Iterator<C> {
632       private final Iterator<A> a = requireNonNull(as.iterator(), "as iterator must not be null.");
633       private final Iterator<B> b = requireNonNull(bs.iterator(), "bs iterator must not be null.");
634 
635       @Override public boolean hasNext() {
636         return a.hasNext() && b.hasNext();
637       }
638 
639       @Override public C next() {
640         return f.apply(a.next(), b.next());
641       }
642 
643       @Override public void remove() {
644         throw new UnsupportedOperationException();
645       }
646     }
647   }
648 
649   /**
650    * Intersperse an element between all the elements in an iterable.
651    *
652    * @param <A> the type of the elements.
653    * @param as the source iterable.
654    * @param a the element to intersperse between the source elements.
655    * @return a new Iterable that intersperses the element between the source.
656    * @since 2.3
657    */
658   public static <A> Iterable<A> intersperse(final Iterable<? extends A> as, final A a) {
659     return intersperse(as, ofInstance(a));
660   }
661 
662   /**
663    * Intersperse an element between all the elements in an iterable.
664    *
665    * @param <A> the type of the elements.
666    * @param as the source iterable.
667    * @param a the supplier of elements to intersperse between the source
668    * elements.
669    * @return a new Iterable that intersperses the element between the source.
670    * @since 2.3
671    */
672   public static <A> Iterable<A> intersperse(final Iterable<? extends A> as, final Supplier<A> a) {
673     return new Intersperse<>(as, a);
674   }
675 
676   static final class Intersperse<A> implements Iterable<A> {
677     private final Iterable<? extends A> as;
678     private final Supplier<A> a;
679 
680     Intersperse(final Iterable<? extends A> as, final Supplier<A> a) {
681       this.as = as;
682       this.a = a;
683     }
684 
685     @Override public Iterator<A> iterator() {
686       return new Iterators.Abstract<A>() {
687         private final Iterator<? extends A> it = as.iterator();
688         private boolean inter = false;
689 
690         @Override protected A computeNext() {
691           if (!it.hasNext()) {
692             return endOfData();
693           }
694           try {
695             return inter ? a.get() : it.next();
696           } finally {
697             inter = !inter;
698           }
699         }
700       };
701     }
702   }
703 
704   /**
705    * Return the size of an iterable. In most cases this function is required to
706    * walk the entire iterable to determine the result. Consider this an O(n)
707    * complexity function.
708    *
709    * @param as iterable to compute the size of
710    * @param <A> element type
711    * @return number of elements in the iterable
712    * @since 3.0
713    */
714   public static <A> int size(final Iterable<A> as) {
715     if (as instanceof Collection) {
716       return ((Collection<?>) as).size();
717     } else {
718       final Iterator<A> iterator = as.iterator();
719       int count = 0;
720       while (iterator.hasNext()) {
721         iterator.next();
722         count++;
723       }
724       return count;
725     }
726   }
727 
728   /**
729    * Transform an interable by mapping a function across each of its elements
730    *
731    * @param as the source iterable
732    * @param f function to apply to all the elements of as
733    * @param <A> original iterable type
734    * @param <B> output iterable type
735    * @return new iterable containing the transformed values produced by f#apply
736    * @since 3.0
737    * @deprecated function provided to make migration easier prefer to use #map
738    * where possible
739    */
740   @Deprecated public static <A, B> Iterable<B> transform(final Iterable<A> as, final Function<? super A, ? extends B> f) {
741     return map(as, f);
742   }
743 
744   /**
745    * Apply the input function to each of the elements of the input iterable
746    * returning a new iterable
747    *
748    * @param as the source iterable
749    * @param f function to apply to all the elements of as
750    * @param <A> original iterable type
751    * @param <B> output iterable type
752    * @return new iterable containing values produced by f#apply called on each
753    * element
754    * @since 3.0
755    */
756   public static <A, B> Iterable<B> map(final Iterable<A> as, final Function<? super A, ? extends B> f) {
757     return new Mapped<>(as, f);
758   }
759 
760   static final class Mapped<A, B> implements Iterable<B> {
761     private final Iterable<? extends A> as;
762     private final Function<? super A, ? extends B> f;
763 
764     Mapped(final Iterable<? extends A> as, final Function<? super A, ? extends B> f) {
765       this.as = as;
766       this.f = f;
767     }
768 
769     @Override public Iterator<B> iterator() {
770       return new Iterators.Abstract<B>() {
771         private final Iterator<? extends A> it = as.iterator();
772 
773         @Override protected B computeNext() {
774           if (!it.hasNext()) {
775             return endOfData();
776           }
777           return f.apply(it.next());
778         }
779       };
780     }
781   }
782 
783   /**
784    * Remove elements from the input iterable for which the predicate returns
785    * false
786    *
787    * @param as original iterable
788    * @param p predicate to filter by
789    * @param <A> element type
790    * @return new iterable containing only those elements for which p#test
791    * returns true
792    * @since 3.0
793    */
794   public static <A> Iterable<A> filter(final Iterable<A> as, final Predicate<? super A> p) {
795     return new Filter<>(as, p);
796   }
797 
798   static final class Filter<A> implements Iterable<A> {
799     private final Iterable<? extends A> as;
800     private final Predicate<? super A> p;
801 
802     Filter(final Iterable<? extends A> as, final Predicate<? super A> p) {
803       this.as = as;
804       this.p = p;
805     }
806 
807     @Override public Iterator<A> iterator() {
808       return new Iterators.Abstract<A>() {
809         private final Iterator<? extends A> it = as.iterator();
810 
811         @Override protected A computeNext() {
812           if (!it.hasNext()) {
813             return endOfData();
814           }
815           while (it.hasNext()) {
816             final A a = it.next();
817             if (p.test(a)) {
818               return a;
819             }
820           }
821           return endOfData();
822         }
823       };
824     }
825   }
826 
827   /**
828    * Join {@literal Iterable<Iterable<A>>} down to {@literal Iterable<A>}. The
829    * resulting iterable will exhaust the first input iterable in order before
830    * returning values from the second. Input iterables must not be null and must
831    * not contain null.
832    *
833    * @param ias one or more iterable to merge into the final iterable result,
834    * must not be null and must not return null
835    * @param <A> element type
836    * @return single level iterable with all the elements of the original
837    * iterables
838    * @since 3.0
839    */
840   public static <A> Iterable<A> join(final Iterable<? extends Iterable<? extends A>> ias) {
841     return new Join<>(ias);
842   }
843 
844   static final class Join<A> extends IterableToString<A> {
845     private final Iterable<? extends Iterable<? extends A>> ias;
846 
847     public Join(final Iterable<? extends Iterable<? extends A>> ias) {
848       this.ias = ias;
849     }
850 
851     @Override public Iterator<A> iterator() {
852       return new Iter<>(ias);
853     }
854 
855     static class Iter<A> extends Iterators.Abstract<A> {
856       final Queue<Iterator<? extends A>> qas = new LinkedList<>();
857 
858       public Iter(final Iterable<? extends Iterable<? extends A>> ias) {
859         for (final Iterable<? extends A> a : ias) {
860           qas.add(requireNonNull(a.iterator()));
861         }
862       }
863 
864       @Override protected A computeNext() {
865         while (!qas.isEmpty() && !qas.peek().hasNext()) {
866           qas.remove();
867         }
868         if (qas.isEmpty()) {
869           return endOfData();
870         }
871         return qas.peek().next();
872       }
873     }
874   }
875 
876   /**
877    * Concatenate a series of iterables into a single iterable. Returns an empty
878    * iterable if no iterables are supplied. Input iterables must not be null and
879    * must not contain null.
880    *
881    * @param as any number of iterables containing A
882    * @param <A> super type of contained by all input iterables
883    * @return new iterable containing all the elements of the input iterables
884    * @since 3.0
885    */
886   @SafeVarargs public static <A> Iterable<A> concat(final Iterable<? extends A>... as) {
887     return as.length > 0 ? join(Arrays.asList(as)) : emptyIterable();
888   }
889 
890   /**
891    * Check if the iterable contains any elements that match the predicate.
892    *
893    * @param as iterable to compare for matching elements
894    * @param p predicate to test for matching elements
895    * @param <A> type of elements inside the input iterable
896    * @return true if any element in the iterable returns true for the input
897    * predicate otherwise false. False for an empty iterable.
898    * @since 3.0
899    */
900   public static <A> boolean any(final Iterable<? extends A> as, final Predicate<? super A> p) {
901     return !isEmpty().test(filter(as, p));
902   }
903 
904   /**
905    * Check if all elements in the input iterable match the input predicate
906    *
907    * @param as iterable to compare for matching elements
908    * @param p predicate to test for matching elements
909    * @param <A> type of elements inside the input iterable
910    * @return true if all elements in the iterable return true for the input
911    * predicate otherwise false. True for an empty iterable.
912    * @since 3.0
913    */
914   public static <A> boolean all(final Iterable<? extends A> as, final Predicate<? super A> p) {
915     return isEmpty().test(filter(as, p.negate()));
916   }
917 
918   /**
919    * Returns an infinite Iterable constructed by applying the given iteration
920    * function starting at the given value.
921    *
922    * @param <A> type of the elements
923    * @param f The iteration function, must not return null
924    * @param start The value to begin iterating from.
925    * @return An infinite Iterable of repeated applications of {@code f} to
926    * {@code start}.
927    * @since 2.4
928    */
929   public static <A> Iterable<A> iterate(final Function<? super A, ? extends A> f, final A start) {
930     return new IteratingIterable<>(f, start);
931   }
932 
933   /**
934    * Infinite iterable that repeatedly applies {@code f} to {@code start}
935    */
936   static final class IteratingIterable<A> implements Iterable<A> {
937     private final Function<? super A, ? extends A> f;
938     private final A start;
939 
940     private IteratingIterable(final Function<? super A, ? extends A> f, final A start) {
941       this.f = requireNonNull(f, "f");
942       this.start = start;
943     }
944 
945     @Override public Iterator<A> iterator() {
946       return new Iter<>(f, start);
947     }
948 
949     static final class Iter<A> extends Iterators.Unmodifiable<A> {
950       private final Function<? super A, ? extends A> f;
951       private A current;
952 
953       Iter(final Function<? super A, ? extends A> f, final A start) {
954         this.f = f;
955         this.current = start;
956       }
957 
958       @Override public boolean hasNext() {
959         return true;
960       }
961 
962       @Override public A next() {
963         final A value = current;
964         current = f.apply(current);
965         return value;
966       }
967     }
968   }
969 
970   /**
971    * Builds an Iterable from a seed value until {@code f} returns {@code none()}
972    * .
973    *
974    * @param <A> type of the returned elements.
975    * @param <B> type of the elements for which {@code f} is applied.
976    * @param f The function that returns some(pair(a, b)), in which case
977    * {@code a} is the next element of the resulting Iterable and {@code b} is
978    * used as the input value for the next call of {@code f}, or {@code none()}
979    * if it is done producing the elements. f must not be null and must not
980    * return a pair containing null.
981    * @param seed The start value to begin the unfold.
982    * @return An Iterable that is a result of unfolding.
983    * @since 2.4
984    */
985   public static <A, B> Iterable<A> unfold(final Function<? super B, Option<Pair<A, B>>> f, final B seed) {
986     return new UnfoldingIterable<>(f, seed);
987   }
988 
989   /**
990    * Iterable that repeatedly applies {@code f} until it returns {@code none()}
991    */
992   static final class UnfoldingIterable<A, B> extends IterableToString<A> {
993     private final Function<? super B, Option<Pair<A, B>>> f;
994     private final B seed;
995 
996     private UnfoldingIterable(final Function<? super B, Option<Pair<A, B>>> f, final B seed) {
997       this.f = requireNonNull(f, "f");
998       this.seed = seed;
999     }
1000 
1001     @Override public Iterator<A> iterator() {
1002       return new Iter<>(f, seed);
1003     }
1004 
1005     static final class Iter<A, B> extends Iterators.Abstract<A> {
1006       private final Function<? super B, Option<Pair<A, B>>> f;
1007       private B current;
1008 
1009       Iter(final Function<? super B, Option<Pair<A, B>>> f, final B seed) {
1010         this.f = f;
1011         this.current = seed;
1012       }
1013 
1014       @Override protected A computeNext() {
1015         final Option<Pair<A, B>> option = f.apply(current);
1016         if (option.isDefined()) {
1017           final Pair<A, B> pair = option.get();
1018           current = pair.right();
1019           return pair.left();
1020         } else {
1021           return endOfData();
1022         }
1023       }
1024     }
1025   }
1026 
1027   /**
1028    * Merge a number of already sorted collections of elements into a single
1029    * collection of elements, using the elements natural ordering.
1030    *
1031    * @param <A> collection type
1032    * @param xss collection of already sorted collections, must not be null and
1033    * must not return null
1034    * @return {@code xss} merged in a sorted order
1035    * @since 1.1
1036    */
1037   public static <A extends Comparable<A>> Iterable<A> mergeSorted(final Iterable<? extends Iterable<A>> xss) {
1038     return mergeSorted(xss, Comparator.<A> naturalOrder());
1039   }
1040 
1041   /**
1042    * Merge a number of already sorted collections of elements into a single
1043    * collection of elements.
1044    *
1045    * @param <A> type of the elements
1046    * @param xss already sorted collection of collections, must not be null and
1047    * must not return null
1048    * @param ordering ordering to use when comparing elements, must not be null
1049    * @return {@code xss} merged in a sorted order
1050    * @since 1.1
1051    */
1052   public static <A> Iterable<A> mergeSorted(final Iterable<? extends Iterable<A>> xss, final Comparator<A> ordering) {
1053     return new MergeSortedIterable<>(xss, ordering);
1054   }
1055 
1056   /**
1057    * Add all the elements of the iterable to the collection
1058    *
1059    * @param collectionToModify collection to add elements to
1060    * @param elementsToAdd source of addtional elements
1061    * @param <A> element type
1062    * @return true if the collectionToModify was changed
1063    * @since 3.0
1064    */
1065   @SuppressWarnings("unchecked") public static <A> boolean addAll(final Collection<A> collectionToModify, final Iterable<? extends A> elementsToAdd) {
1066     if (elementsToAdd instanceof Collection) {
1067       return collectionToModify.addAll((Collection<? extends A>) elementsToAdd);
1068     }
1069     return Iterators.addAll(collectionToModify, requireNonNull(elementsToAdd).iterator());
1070   }
1071 
1072   /**
1073    * Merges multiple sorted Iterables into one, sorted iterable.
1074    */
1075   static final class MergeSortedIterable<A> extends IterableToString<A> {
1076     private final Iterable<? extends Iterable<A>> xss;
1077     private final Comparator<A> comparator;
1078 
1079     MergeSortedIterable(final Iterable<? extends Iterable<A>> xss, final Comparator<A> comparator) {
1080       this.xss = requireNonNull(xss, "xss");
1081       this.comparator = requireNonNull(comparator, "comparator");
1082     }
1083 
1084     @Override public Iterator<A> iterator() {
1085       return new Iter<>(xss, comparator);
1086     }
1087 
1088     private static final class Iter<A> extends Iterators.Abstract<A> {
1089       private final TreeSet<Iterators.Peeking<A>> xss;
1090 
1091       private Iter(final Iterable<? extends Iterable<A>> xss, final Comparator<A> c) {
1092         this.xss = new TreeSet<>(peekingIteratorComparator(c));
1093         addAll(this.xss, map(filter(xss, isEmpty().negate()), i -> peekingIterator(i.iterator())));
1094       }
1095 
1096       @Override protected A computeNext() {
1097         final Option<Iterators.Peeking<A>> currFirstOption = first(xss);
1098         if (!currFirstOption.isDefined()) {
1099           return endOfData();
1100         }
1101         final Iterators.Peeking<A> currFirst = currFirstOption.get();
1102 
1103         // We remove the iterator from the set first, before we mutate it,
1104         // otherwise we wouldn't be able to
1105         // properly find it to remove it. Mutation sucks.
1106         xss.remove(currFirst);
1107 
1108         final A next = currFirst.next();
1109         if (currFirst.hasNext()) {
1110           xss.add(currFirst);
1111         }
1112         return next;
1113       }
1114 
1115       private Comparator<? super Iterators.Peeking<A>> peekingIteratorComparator(final Comparator<A> comparator) {
1116         return (lhs, rhs) -> (lhs == rhs) ? 0 : comparator.compare(lhs.peek(), rhs.peek());
1117       }
1118     }
1119   }
1120 
1121   /**
1122    * Return an infinite iterable that cycles through the input values in order
1123    * in a loop. If no elements are provided returns an empty iterable. Does not
1124    * support element removal via Iterator#remove.
1125    *
1126    * @param as input values to cycle through
1127    * @param <A> returned elements
1128    * @return an infinite iterable containing the original elements
1129    * @since 3.0
1130    */
1131   @SafeVarargs public static <A> Iterable<A> cycle(final A... as) {
1132     if (as.length > 0) {
1133       return new Cycle<>(Arrays.asList(as));
1134     } else {
1135       return emptyIterable();
1136     }
1137   }
1138 
1139   /**
1140    * Return an infinite iterable that cycles through the input values in order
1141    * in a loop. If no elements are provided returns an empty iterable. Does not
1142    * support element removal via Iterator#remove.
1143    *
1144    * @param as input values to cycle through must not be null
1145    * @param <A> returned elements
1146    * @return an infinite iterable containing the original elements
1147    * @since 3.0
1148    */
1149   public static <A> Iterable<A> cycle(final Iterable<? extends A> as) {
1150     return new Cycle<>(as);
1151   }
1152 
1153   static final class Cycle<A> implements Iterable<A> {
1154     final Iterable<? extends A> as;
1155 
1156     Cycle(final Iterable<? extends A> as) {
1157       this.as = requireNonNull(as);
1158     }
1159 
1160     @Override public Iterator<A> iterator() {
1161       return new Iter<>(as);
1162     }
1163 
1164     static final class Iter<A> extends Iterators.Abstract<A> {
1165       Iterable<? extends A> as;
1166       Iterator<? extends A> ias;
1167 
1168       Iter(final Iterable<? extends A> as) {
1169         this.as = as;
1170         this.ias = as.iterator();
1171       }
1172 
1173       @Override protected A computeNext() {
1174         if (!ias.hasNext() && !(ias = as.iterator()).hasNext()) {
1175           return endOfData();
1176         }
1177         return ias.next();
1178       }
1179     }
1180 
1181     @Override public String toString() {
1182       return makeString(as, "[", ", ", "...]", 100);
1183     }
1184   }
1185 
1186   /**
1187    * Pretty print an Iterable.
1188    *
1189    * Printing following this pattern:
1190    * {@literal <start><element><sep><element><end>} If the iterable would result
1191    * in a String with length more than maxLength printing follows this pattern:
1192    * {@literal <start><element><sep><element>...<end>}
1193    *
1194    * @param as the iterable to print must not be null
1195    * @param start prefix to start the printing with
1196    * @param sep separator to use between each element
1197    * @param end suffic to end the printing with
1198    * @param maxLength limit the length of the resulting string
1199    * @param <A> type of the elements in the iterable
1200    * @return a pretty printed copy of the input iterable
1201    * @since 3.0
1202    */
1203   public static <A> String makeString(final Iterable<? extends A> as, final String start, final String sep, final String end, final int maxLength) {
1204     final StringBuilder b = new StringBuilder();
1205     b.append(start);
1206     final Iterator<? extends A> ias = requireNonNull(as).iterator();
1207 
1208     if (ias.hasNext()) {
1209       b.append(String.valueOf(ias.next()));
1210     }
1211     while (ias.hasNext()) {
1212       if (b.length() >= maxLength) {
1213         break;
1214       }
1215 
1216       b.append(sep);
1217       final String value = String.valueOf(ias.next());
1218       b.append(value);
1219     }
1220     if (ias.hasNext()) {
1221       b.append("...");
1222     }
1223     b.append(end);
1224     return b.toString();
1225   }
1226 
1227   /**
1228    * Pretty print an Iterable.
1229    *
1230    * Printing following this pattern:
1231    * {@literal <start><element><sep><element><end>} If the iterable would result
1232    * in a String with length more than 100 characters printing follows this
1233    * pattern: {@literal <start><element><sep><element>...<end>}
1234    *
1235    * @param as the iterable to print must not be null
1236    * @param start prefix to start the printing with
1237    * @param sep separator to use between each element
1238    * @param end suffic to end the printing with
1239    * @param <A> type of the elements in the iterable
1240    * @return a pretty printed copy of the input iterable
1241    * @see #makeString(Iterable, String, String, String, int) pretty print
1242    * iterable with a custom length
1243    * @since 3.0
1244    */
1245   public static <A> String makeString(final Iterable<? extends A> as, final String start, final String sep, final String end) {
1246     return makeString(as, start, sep, end, 100);
1247   }
1248 
1249   /**
1250    * Makes a lazy copy of {@code xs}.
1251    *
1252    * @param <A> type of elements in {@code xs}
1253    * @param xs {@code Iterable} to be memoized
1254    * @return lazy copy of {@code as}
1255    * @since 1.1
1256    */
1257   public static <A> Iterable<A> memoize(final Iterable<A> xs) {
1258     return new Memoizer<>(xs);
1259   }
1260 
1261   /**
1262    * Memoizing iterable, maintains a lazily computed linked list of nodes.
1263    */
1264   static final class Memoizer<A> extends IterableToString<A> {
1265     private final Node<A> head;
1266 
1267     Memoizer(final Iterable<A> delegate) {
1268       head = nextNode(delegate.iterator());
1269     }
1270 
1271     @Override public Iterator<A> iterator() {
1272       return new Iter<>(head);
1273     }
1274 
1275     private static <A> Node<A> nextNode(final Iterator<A> delegate) {
1276       return delegate.hasNext() ? new Lazy<>(delegate) : new End<>();
1277     }
1278 
1279     /**
1280      * Linked list node.
1281      */
1282     interface Node<A> {
1283       boolean isEnd();
1284 
1285       A value();
1286 
1287       /**
1288        * Get the next Node.
1289        *
1290        * @return a new Node
1291        * @throws java.util.NoSuchElementException if this is terminal
1292        */
1293       Node<A> next() throws NoSuchElementException;
1294     }
1295 
1296     /**
1297      * Lazily computes the next node. Has a value so is not an end.
1298      */
1299     static class Lazy<A> extends LazyReference<Node<A>> implements Node<A> {
1300       private final Iterator<A> delegate;
1301       private final A value;
1302 
1303       Lazy(final Iterator<A> delegate) {
1304         this.delegate = delegate;
1305         this.value = delegate.next();
1306       }
1307 
1308       @Override protected Node<A> create() throws Exception {
1309         return nextNode(delegate);
1310       }
1311 
1312       @Override public Node<A> next() throws NoSuchElementException {
1313         return get();
1314       }
1315 
1316       @Override public boolean isEnd() {
1317         return false;
1318       }
1319 
1320       @Override public A value() {
1321         return value;
1322       }
1323     }
1324 
1325     static class End<A> implements Node<A> {
1326       @Override public boolean isEnd() {
1327         return true;
1328       }
1329 
1330       // /CLOVER:OFF
1331       @Override public Node<A> next() {
1332         throw new NoSuchElementException();
1333       }
1334 
1335       @Override public A value() {
1336         throw new NoSuchElementException();
1337       }
1338       // /CLOVER:ON
1339     }
1340 
1341     static class Iter<A> extends Iterators.Abstract<A> {
1342       Node<A> node;
1343 
1344       Iter(final Node<A> node) {
1345         this.node = node;
1346       }
1347 
1348       @Override protected A computeNext() {
1349         if (node.isEnd()) {
1350           return endOfData();
1351         }
1352         try {
1353           return node.value();
1354         } finally {
1355           node = node.next();
1356         }
1357       }
1358     }
1359   }
1360 
1361   /**
1362    * Class supports the implementation of {@link Iterables#memoize(Iterable)}
1363    * and is not intended for general use.
1364    *
1365    * Lazily loaded reference that is not constructed until required. This class
1366    * is used to maintain a reference to an object that is expensive to create
1367    * and must be constructed once and once only. This reference behaves as
1368    * though the <code>final</code> keyword has been used (you cannot reset it
1369    * once it has been constructed). Object creation is guaranteed to be
1370    * thread-safe and the first thread that calls {@link #get()} will be the one
1371    * that creates it.
1372    * <p>
1373    * Usage: clients need to implement the {@link #create()} method to return the
1374    * object this reference will hold.
1375    * <p>
1376    * For instance:
1377    * <p>
1378    *
1379    * <pre>
1380    * final LazyReference&lt;MyObject&gt; ref = new LazyReference() {
1381    *   protected MyObject create() throws Exception {
1382    *     // Do expensive object construction here
1383    *     return new MyObject();
1384    *   }
1385    * };
1386    * </pre>
1387    *
1388    * Then call {@link #get()} to get a reference to the referenced object:
1389    *
1390    * <pre>
1391    * MyObject myLazyLoadedObject = ref.get()
1392    * </pre>
1393    *
1394    * NOTE: Interruption policy is that if you want to be cancellable while
1395    * waiting for another thread to create the value, instead of calling
1396    * {@link #get()} call {@link #getInterruptibly()}. However, If your
1397    * {@link #create()} method is interrupted and throws an
1398    * {@link InterruptedException}, it is treated as an application exception and
1399    * will be the causal exception inside the runtime
1400    * {@link InitializationException} that {@link #get()} or
1401    * {@link #getInterruptibly()} throws and your {@link #create()} will not be
1402    * called again.
1403    * <p>
1404    * This class is NOT {@link Serializable}.
1405    * <p>
1406    * Implementation note. This class extends {@link WeakReference} as
1407    * {@link Reference} does not have a public constructor. WeakReference is
1408    * preferable as it does not have any members and therefore doesn't increase
1409    * the memory footprint. As we never pass a referent through to the
1410    * super-class and override {@link #get()}, the garbage collection semantics
1411    * of WeakReference are irrelevant. The referenced object will not become
1412    * eligible for GC unless the object holding the reference to this object is
1413    * collectible.
1414    *
1415    * @param <T> the type of the contained element.
1416    */
1417   // @ThreadSafe
1418   static abstract class LazyReference<T> extends WeakReference<T> implements Supplier<T> {
1419 
1420     private final Sync sync = new Sync();
1421 
1422     public LazyReference() {
1423       super(null);
1424     }
1425 
1426     /**
1427      * The object factory method, guaranteed to be called once and only once.
1428      *
1429      * @return the object that {@link #get()} and {@link #getInterruptibly()}
1430      * will return.
1431      * @throws Exception if anything goes wrong, rethrown as an
1432      * InitializationException from {@link #get()} and
1433      * {@link #getInterruptibly()}
1434      */
1435     protected abstract T create() throws Exception;
1436 
1437     /**
1438      * Get the lazily loaded reference in a non-cancellable manner. If your
1439      * <code>create()</code> method throws an Exception calls to
1440      * <code>get()</code> will throw an InitializationException which wraps the
1441      * previously thrown exception.
1442      *
1443      * @return the object that {@link #create()} created.
1444      * @throws InitializationException if the {@link #create()} method throws an
1445      * exception. The {@link InitializationException#getCause()} will contain
1446      * the exception thrown by the {@link #create()} method
1447      */
1448     @Override public final T get() {
1449       boolean interrupted = false;
1450       try {
1451         while (true) {
1452           try {
1453             return getInterruptibly();
1454           } catch (final InterruptedException ignore) {
1455             // ignore and try again
1456             interrupted = true;
1457           }
1458         }
1459       } finally {
1460         if (interrupted) {
1461           Thread.currentThread().interrupt();
1462         }
1463       }
1464     }
1465 
1466     /**
1467      * Get the lazily loaded reference in a cancellable manner. If your
1468      * <code>create()</code> method throws an Exception, calls to
1469      * <code>get()</code> will throw a RuntimeException which wraps the
1470      * previously thrown exception.
1471      *
1472      * @return the object that {@link #create()} created.
1473      * @throws InitializationException if the {@link #create()} method throws an
1474      * exception. The {@link InitializationException#getCause()} will contain
1475      * the exception thrown by the {@link #create()} method
1476      * @throws InterruptedException If the calling thread is Interrupted while
1477      * waiting for another thread to create the value (if the creating thread is
1478      * interrupted while blocking on something, the {@link InterruptedException}
1479      * will be thrown as the causal exception of the
1480      * {@link InitializationException} to everybody calling this method).
1481      */
1482     public final T getInterruptibly() throws InterruptedException {
1483       if (!sync.isDone()) {
1484         sync.run();
1485       }
1486 
1487       try {
1488         return sync.get();
1489       } catch (final ExecutionException e) {
1490         throw new InitializationException(e);
1491       }
1492     }
1493 
1494     /**
1495      * Has the {@link #create()} reference been initialized.
1496      *
1497      * @return true if the task is complete
1498      */
1499     public final boolean isInitialized() {
1500       return sync.isDone();
1501     }
1502 
1503     /**
1504      * Cancel the initializing operation if it has not already run. Will try and
1505      * interrupt if it is currently running.
1506      */
1507     public final void cancel() {
1508       sync.cancel(true);
1509     }
1510 
1511     /**
1512      * If the factory {@link LazyReference#create()} method threw an exception,
1513      * this wraps it.
1514      */
1515     public static class InitializationException extends RuntimeException {
1516       private static final long serialVersionUID = 3638376010285456759L;
1517 
1518       InitializationException(final ExecutionException e) {
1519         super((e.getCause() != null) ? e.getCause() : e);
1520       }
1521     }
1522 
1523     static final class State {
1524       static final int INIT = 0;
1525       static final int RUNNING = 1;
1526       static final int RAN = 2;
1527       static final int CANCELLED = 4;
1528     }
1529 
1530     /**
1531      * Synchronization control for LazyReference. Note that this must be a
1532      * non-static inner class in order to invoke the protected <tt>create</tt>
1533      * method. Taken from FutureTask AQS implementation and pruned to be as
1534      * compact as possible.
1535      *
1536      * Uses AQS sync state to represent run status.
1537      */
1538     private final class Sync extends AbstractQueuedSynchronizer {
1539 
1540       static final int IGNORED = 0;
1541 
1542       /**
1543        * only here to shut up the compiler warnings, the outer class is NOT
1544        * serializable
1545        */
1546       private static final long serialVersionUID = -1645412544240373524L;
1547 
1548       /** The result to return from get() */
1549       private T result;
1550       /** The exception to throw from get() */
1551       private Throwable exception;
1552 
1553       /**
1554        * The thread running task. When nulled after set/cancel, this indicates
1555        * that the results are accessible. Must be volatile, to ensure visibility
1556        * upon completion.
1557        */
1558       private volatile Thread runner;
1559 
1560       private boolean ranOrCancelled(final int state) {
1561         return (state & (State.RAN | State.CANCELLED)) != State.INIT;
1562       }
1563 
1564       /**
1565        * Implements AQS base acquire to succeed if ran or cancelled
1566        */
1567       @Override protected int tryAcquireShared(final int ignore) {
1568         return isDone() ? 1 : -1;
1569       }
1570 
1571       /**
1572        * Implements AQS base release to always signal after setting final done
1573        * status by nulling runner thread.
1574        */
1575       @Override protected boolean tryReleaseShared(final int ignore) {
1576         runner = null;
1577         return true;
1578       }
1579 
1580       boolean isDone() {
1581         return ranOrCancelled(getState()) && (runner == null);
1582       }
1583 
1584       T get() throws InterruptedException, ExecutionException {
1585         acquireSharedInterruptibly(IGNORED);
1586         if (getState() == State.CANCELLED) {
1587           throw new CancellationException();
1588         }
1589         if (exception != null) {
1590           throw new ExecutionException(exception);
1591         }
1592         return result;
1593       }
1594 
1595       void set(final T v) {
1596         for (;;) {
1597           final int s = getState();
1598           if (s == State.RAN) {
1599             return;
1600           }
1601           if (s == State.CANCELLED) {
1602             // aggressively release to set runner to null,
1603             // in case we are racing with a cancel request
1604             // that will try to interrupt runner
1605             releaseShared(IGNORED);
1606             return;
1607           }
1608           if (compareAndSetState(s, State.RAN)) {
1609             result = v;
1610             releaseShared(IGNORED);
1611             return;
1612           }
1613         }
1614       }
1615 
1616       void setException(final Throwable t) {
1617         for (;;) {
1618           final int s = getState();
1619           if (s == State.RAN) {
1620             return;
1621           }
1622           if (s == State.CANCELLED) {
1623             // aggressively release to set runner to null,
1624             // in case we are racing with a cancel request
1625             // that will try to interrupt runner
1626             releaseShared(0);
1627             return;
1628           }
1629           if (compareAndSetState(s, State.RAN)) {
1630             exception = t;
1631             result = null;
1632             releaseShared(0);
1633             return;
1634           }
1635         }
1636       }
1637 
1638       void cancel(final boolean mayInterruptIfRunning) {
1639         for (;;) {
1640           final int s = getState();
1641           if (ranOrCancelled(s)) {
1642             return;
1643           }
1644           if (compareAndSetState(s, State.CANCELLED)) {
1645             break;
1646           }
1647         }
1648         if (mayInterruptIfRunning) {
1649           final Thread r = runner;
1650           if (r != null) {
1651             r.interrupt();
1652           }
1653         }
1654         releaseShared(IGNORED);
1655       }
1656 
1657       void run() {
1658         if ((getState() != State.INIT) || !compareAndSetState(State.INIT, State.RUNNING)) {
1659           if (runner == Thread.currentThread()) {
1660             throw new IllegalMonitorStateException("Not reentrant!");
1661           }
1662           return;
1663         }
1664         try {
1665           runner = Thread.currentThread();
1666           set(create());
1667         } catch (final Throwable ex) {
1668           setException(ex);
1669         }
1670       }
1671     }
1672   }
1673 }