View Javadoc
1   /*
2    * This file is part of ***  M y C o R e  ***
3    * See http://www.mycore.de/ for details.
4    *
5    * MyCoRe is free software: you can redistribute it and/or modify
6    * it under the terms of the GNU General Public License as published by
7    * the Free Software Foundation, either version 3 of the License, or
8    * (at your option) any later version.
9    *
10   * MyCoRe is distributed in the hope that it will be useful,
11   * but WITHOUT ANY WARRANTY; without even the implied warranty of
12   * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13   * GNU General Public License for more details.
14   *
15   * You should have received a copy of the GNU General Public License
16   * along with MyCoRe.  If not, see <http://www.gnu.org/licenses/>.
17   */
18  
19  package org.mycore.util.concurrent;
20  
21  import java.util.Comparator;
22  import java.util.concurrent.CompletableFuture;
23  import java.util.concurrent.PriorityBlockingQueue;
24  import java.util.concurrent.ThreadPoolExecutor;
25  import java.util.function.Supplier;
26  
27  /**
28   * A {@link CompletableFuture} encapsulates a {@link Supplier} with an <code>AsyncSupply</code>.
29   * This make a {@link ThreadPoolExecutor} with a {@link PriorityBlockingQueue} useless. To
30   * regain the {@link Comparable} feature we have to unwrap the <code>AsyncSupply</code> and
31   * compare the original {@link Runnable}.
32   * 
33   * <a href="http://stackoverflow.com/questions/34866757/how-do-i-use-completablefuture-supplyasync-together-with-priorityblockingqueue">stackoverflow</a>
34   * 
35   * Note: this comparator imposes orderings that are inconsistent with equals.
36   * 
37   * @author Matthias Eichner
38   */
39  public class MCRRunnableComperator implements Comparator<Runnable> {
40  
41      @SuppressWarnings({ "unchecked", "rawtypes" })
42      @Override
43      public int compare(Runnable o1, Runnable o2) {
44          if (isComparable(o1, o2)) {
45              return ((Comparable) o1).compareTo(o2);
46          }
47          return -1;
48      }
49  
50      private boolean isComparable(Runnable o1, Runnable o2) {
51          return o1 instanceof Comparable && o2 instanceof Comparable;
52      }
53  
54  }