├── .gitignore ├── .travis.yml ├── README.md ├── build.gradle ├── gradle.properties ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat ├── settings.gradle └── src ├── main └── java │ └── me │ └── ronshapiro │ └── rx │ └── priority │ └── PriorityScheduler.java └── test └── java └── me └── ronshapiro └── rx └── priority └── PrioritySchedulerTest.java /.gitignore: -------------------------------------------------------------------------------- 1 | .DS_Store 2 | /build 3 | /out 4 | /.idea 5 | *.iml 6 | /.gradle 7 | local.properties -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: java 2 | jdk: 3 | - oraclejdk7 4 | - openjdk6 5 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # PriorityScheduler - RxJava 2 | [![Build Status](https://travis-ci.org/ronshapiro/rxjava-priority-scheduler.svg?branch=master)](https://travis-ci.org/ronshapiro/rxjava-priority-scheduler) 3 | 4 | While thinking about the intersection of [RxJava](https://github.com/ReactiveX/RxJava) and [Android](https://github.com/ReactiveX/RxAndroid), I realized there was no default scheduler in the library that allowed for prioritizing actions before others, similar to how [Volley](http://developer.android.com/training/volley/index.html)'s [Request.Priority](https://github.com/mcxiaoke/android-volley/blob/bea90385b1b847553a86425347fc3f560db98581/src/com/android/volley/Request.java#L503). I decided to try and work something together and this is what I initially came up with. Some of the threading seems a bit strange and the [Worker](https://github.com/ReactiveX/RxJava/blob/7dbed13ccc68bba80816311fe7c27126fe6d6d8f/src/main/java/rx/Scheduler.java#L60) works (no pun intended) a bit differently than others, but it seems to do the trick. Gladly accepting comments/pull requests! 5 | 6 | ## Sample Usage 7 | 8 | ```java 9 | final int PRIORITY_HIGH = 10; 10 | final int PRIORITY_LOW = 1; 11 | 12 | PriorityScheduler scheduler = new PriorityScheduler(); 13 | Observable.just(1, 2, 3, 4, 5) 14 | .subscribeOn(scheduler.priority(PRIORITY_LOW)) 15 | .subscribe(System.out::println); 16 | 17 | Observable.just(6, 7, 8, 9, 10) 18 | .subscribeOn(scheduler.priority(PRIORITY_HIGH)) 19 | .subscribe(System.out::println); 20 | ``` 21 | 22 | ### Priorities 23 | Priorties are simply ints ordered in increasing order. An action with a priority higher than another will be scheduled before (note that actions with the same priority may run in any order). Priorities may be any valid integer; you may want to define: 24 | ```java 25 | private static final int PRIORITY_WHENEVER = Integer.MIN_VALUE; 26 | ```` 27 | and/or 28 | ```java 29 | private static final int PRIORITY_NEXT = Integer.MAX_VALUE; 30 | ``` 31 | 32 | ## Download 33 | 34 | Gradle: 35 | ```groovy 36 | compile 'me.ronshapiro.rx.priority:priority:0.2' 37 | ``` 38 | 39 | Since this is still a nascent idea, if you're using this library, please let me know ([@rdshapiro](https://twitter.com/rdshapiro)) how it's going! -------------------------------------------------------------------------------- /build.gradle: -------------------------------------------------------------------------------- 1 | apply plugin: 'java' 2 | 3 | sourceCompatibility = 1.6 4 | version = '0.2' 5 | 6 | repositories { 7 | mavenCentral() 8 | } 9 | 10 | dependencies { 11 | compile 'io.reactivex:rxjava:1.0.4' 12 | testCompile group: 'junit', name: 'junit', version: '4.11' 13 | } 14 | 15 | def GRADLE_PUSH_VERSION_SHA = '0125ca29579b7c2aa86690a8ff7dece424c6aa76' 16 | apply(from: "https://raw.githubusercontent.com/ronshapiro/gradle-mvn-push/$GRADLE_PUSH_VERSION_SHA/gradle-mvn-push.gradle") -------------------------------------------------------------------------------- /gradle.properties: -------------------------------------------------------------------------------- 1 | VERSION_NAME=0.2 2 | VERSION_CODE=2 3 | GROUP=me.ronshapiro.rx.priority 4 | 5 | POM_DESCRIPTION=A library that encapsulates the repeatable actions of Android Cursors. 6 | POM_URL=https://github.com/ronshapiro/rxjava-priority-scheduler 7 | POM_SCM_URL=https://github.com/ronshapiro/rxjava-priority-scheduler 8 | POM_SCM_CONNECTION=scm:git@github.com:ronshapiro/rxjava-priority-scheduler.git 9 | POM_SCM_DEV_CONNECTION=scm:git@github.com:ronshapiro/rxjava-priority-scheduler.git 10 | POM_LICENCE_NAME=Apache 2.0 11 | POM_LICENCE_URL=https://github.com/ronshapiro/rxjava-priority-scheduler/blob/master/LICENSE.txt 12 | POM_LICENCE_DIST=repo 13 | POM_DEVELOPER_ID=ronshapiro 14 | POM_DEVELOPER_NAME=Ron Shapiro 15 | 16 | POM_NAME=RxJava PriorityScheduler 17 | POM_ARTIFACT_ID=priority 18 | POM_PACKAGING=jar -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ronshapiro/rxjava-priority-scheduler/c8165f5ed0431d0add6d3badc180145415fb8459/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | #Sun Sep 14 20:05:32 EDT 2014 2 | distributionBase=GRADLE_USER_HOME 3 | distributionPath=wrapper/dists 4 | zipStoreBase=GRADLE_USER_HOME 5 | zipStorePath=wrapper/dists 6 | distributionUrl=https\://services.gradle.org/distributions/gradle-2.0-all.zip 7 | -------------------------------------------------------------------------------- /gradlew: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | ############################################################################## 4 | ## 5 | ## Gradle start up script for UN*X 6 | ## 7 | ############################################################################## 8 | 9 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 10 | DEFAULT_JVM_OPTS="" 11 | 12 | APP_NAME="Gradle" 13 | APP_BASE_NAME=`basename "$0"` 14 | 15 | # Use the maximum available, or set MAX_FD != -1 to use that value. 16 | MAX_FD="maximum" 17 | 18 | warn ( ) { 19 | echo "$*" 20 | } 21 | 22 | die ( ) { 23 | echo 24 | echo "$*" 25 | echo 26 | exit 1 27 | } 28 | 29 | # OS specific support (must be 'true' or 'false'). 30 | cygwin=false 31 | msys=false 32 | darwin=false 33 | case "`uname`" in 34 | CYGWIN* ) 35 | cygwin=true 36 | ;; 37 | Darwin* ) 38 | darwin=true 39 | ;; 40 | MINGW* ) 41 | msys=true 42 | ;; 43 | esac 44 | 45 | # For Cygwin, ensure paths are in UNIX format before anything is touched. 46 | if $cygwin ; then 47 | [ -n "$JAVA_HOME" ] && JAVA_HOME=`cygpath --unix "$JAVA_HOME"` 48 | fi 49 | 50 | # Attempt to set APP_HOME 51 | # Resolve links: $0 may be a link 52 | PRG="$0" 53 | # Need this for relative symlinks. 54 | while [ -h "$PRG" ] ; do 55 | ls=`ls -ld "$PRG"` 56 | link=`expr "$ls" : '.*-> \(.*\)$'` 57 | if expr "$link" : '/.*' > /dev/null; then 58 | PRG="$link" 59 | else 60 | PRG=`dirname "$PRG"`"/$link" 61 | fi 62 | done 63 | SAVED="`pwd`" 64 | cd "`dirname \"$PRG\"`/" >&- 65 | APP_HOME="`pwd -P`" 66 | cd "$SAVED" >&- 67 | 68 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 69 | 70 | # Determine the Java command to use to start the JVM. 71 | if [ -n "$JAVA_HOME" ] ; then 72 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 73 | # IBM's JDK on AIX uses strange locations for the executables 74 | JAVACMD="$JAVA_HOME/jre/sh/java" 75 | else 76 | JAVACMD="$JAVA_HOME/bin/java" 77 | fi 78 | if [ ! -x "$JAVACMD" ] ; then 79 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 80 | 81 | Please set the JAVA_HOME variable in your environment to match the 82 | location of your Java installation." 83 | fi 84 | else 85 | JAVACMD="java" 86 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 87 | 88 | Please set the JAVA_HOME variable in your environment to match the 89 | location of your Java installation." 90 | fi 91 | 92 | # Increase the maximum file descriptors if we can. 93 | if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then 94 | MAX_FD_LIMIT=`ulimit -H -n` 95 | if [ $? -eq 0 ] ; then 96 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then 97 | MAX_FD="$MAX_FD_LIMIT" 98 | fi 99 | ulimit -n $MAX_FD 100 | if [ $? -ne 0 ] ; then 101 | warn "Could not set maximum file descriptor limit: $MAX_FD" 102 | fi 103 | else 104 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" 105 | fi 106 | fi 107 | 108 | # For Darwin, add options to specify how the application appears in the dock 109 | if $darwin; then 110 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" 111 | fi 112 | 113 | # For Cygwin, switch paths to Windows format before running java 114 | if $cygwin ; then 115 | APP_HOME=`cygpath --path --mixed "$APP_HOME"` 116 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` 117 | 118 | # We build the pattern for arguments to be converted via cygpath 119 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` 120 | SEP="" 121 | for dir in $ROOTDIRSRAW ; do 122 | ROOTDIRS="$ROOTDIRS$SEP$dir" 123 | SEP="|" 124 | done 125 | OURCYGPATTERN="(^($ROOTDIRS))" 126 | # Add a user-defined pattern to the cygpath arguments 127 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then 128 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" 129 | fi 130 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 131 | i=0 132 | for arg in "$@" ; do 133 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` 134 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option 135 | 136 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition 137 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` 138 | else 139 | eval `echo args$i`="\"$arg\"" 140 | fi 141 | i=$((i+1)) 142 | done 143 | case $i in 144 | (0) set -- ;; 145 | (1) set -- "$args0" ;; 146 | (2) set -- "$args0" "$args1" ;; 147 | (3) set -- "$args0" "$args1" "$args2" ;; 148 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;; 149 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; 150 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; 151 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; 152 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; 153 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; 154 | esac 155 | fi 156 | 157 | # Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules 158 | function splitJvmOpts() { 159 | JVM_OPTS=("$@") 160 | } 161 | eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS 162 | JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME" 163 | 164 | exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@" 165 | -------------------------------------------------------------------------------- /gradlew.bat: -------------------------------------------------------------------------------- 1 | @if "%DEBUG%" == "" @echo off 2 | @rem ########################################################################## 3 | @rem 4 | @rem Gradle startup script for Windows 5 | @rem 6 | @rem ########################################################################## 7 | 8 | @rem Set local scope for the variables with windows NT shell 9 | if "%OS%"=="Windows_NT" setlocal 10 | 11 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 12 | set DEFAULT_JVM_OPTS= 13 | 14 | set DIRNAME=%~dp0 15 | if "%DIRNAME%" == "" set DIRNAME=. 16 | set APP_BASE_NAME=%~n0 17 | set APP_HOME=%DIRNAME% 18 | 19 | @rem Find java.exe 20 | if defined JAVA_HOME goto findJavaFromJavaHome 21 | 22 | set JAVA_EXE=java.exe 23 | %JAVA_EXE% -version >NUL 2>&1 24 | if "%ERRORLEVEL%" == "0" goto init 25 | 26 | echo. 27 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 28 | echo. 29 | echo Please set the JAVA_HOME variable in your environment to match the 30 | echo location of your Java installation. 31 | 32 | goto fail 33 | 34 | :findJavaFromJavaHome 35 | set JAVA_HOME=%JAVA_HOME:"=% 36 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 37 | 38 | if exist "%JAVA_EXE%" goto init 39 | 40 | echo. 41 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 42 | echo. 43 | echo Please set the JAVA_HOME variable in your environment to match the 44 | echo location of your Java installation. 45 | 46 | goto fail 47 | 48 | :init 49 | @rem Get command-line arguments, handling Windowz variants 50 | 51 | if not "%OS%" == "Windows_NT" goto win9xME_args 52 | if "%@eval[2+2]" == "4" goto 4NT_args 53 | 54 | :win9xME_args 55 | @rem Slurp the command line arguments. 56 | set CMD_LINE_ARGS= 57 | set _SKIP=2 58 | 59 | :win9xME_args_slurp 60 | if "x%~1" == "x" goto execute 61 | 62 | set CMD_LINE_ARGS=%* 63 | goto execute 64 | 65 | :4NT_args 66 | @rem Get arguments from the 4NT Shell from JP Software 67 | set CMD_LINE_ARGS=%$ 68 | 69 | :execute 70 | @rem Setup the command line 71 | 72 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 73 | 74 | @rem Execute Gradle 75 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% 76 | 77 | :end 78 | @rem End local scope for the variables with windows NT shell 79 | if "%ERRORLEVEL%"=="0" goto mainEnd 80 | 81 | :fail 82 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 83 | rem the _cmd.exe /c_ return code! 84 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 85 | exit /b 1 86 | 87 | :mainEnd 88 | if "%OS%"=="Windows_NT" endlocal 89 | 90 | :omega 91 | -------------------------------------------------------------------------------- /settings.gradle: -------------------------------------------------------------------------------- 1 | rootProject.name = 'rx-priority-scheduler' -------------------------------------------------------------------------------- /src/main/java/me/ronshapiro/rx/priority/PriorityScheduler.java: -------------------------------------------------------------------------------- 1 | package me.ronshapiro.rx.priority; 2 | 3 | import java.util.concurrent.ExecutorService; 4 | import java.util.concurrent.Executors; 5 | import java.util.concurrent.PriorityBlockingQueue; 6 | import java.util.concurrent.TimeUnit; 7 | import java.util.concurrent.atomic.AtomicInteger; 8 | 9 | import rx.Scheduler; 10 | import rx.Scheduler.Worker; 11 | import rx.Subscription; 12 | import rx.functions.Action0; 13 | import rx.internal.schedulers.ScheduledAction; 14 | import rx.subscriptions.CompositeSubscription; 15 | import rx.subscriptions.Subscriptions; 16 | 17 | import static java.util.concurrent.TimeUnit.MILLISECONDS; 18 | 19 | /** 20 | * A class to be used with RxJava's {@link Scheduler} interface. Though this class is not a {@link 21 | * Scheduler} itself, calling {@link #priority(int)} will return one. E.x.: {@code PriorityScheduler 22 | * scheduler = new PriorityScheduler(); Observable.just(1, 2, 3) .subscribeOn(scheduler.priority(10)) 23 | * .subscribe(); } 24 | */ 25 | public final class PriorityScheduler { 26 | 27 | private final PriorityBlockingQueue queue = 28 | new PriorityBlockingQueue(); 29 | private final AtomicInteger workerCount = new AtomicInteger(); 30 | private final int concurrency; 31 | private ExecutorService executorService; 32 | 33 | /** 34 | * Creates a {@link PriorityScheduler} with as many threads as the machine's available 35 | * processors. 36 | * 37 | * Note: this does not ensure that the priorities will be adheared to exactly, as the 38 | * JVM's threading policy might allow one thread to dequeue an action, then let a second thread 39 | * dequeue the next action, run it, dequeue another, run it, etc. before the first thread runs 40 | * its action. It does however ensure that at the dequeue step, the thread will receive the 41 | * highest priority action available. 42 | */ 43 | public static PriorityScheduler create() { 44 | return new PriorityScheduler(Runtime.getRuntime().availableProcessors()); 45 | } 46 | 47 | /** 48 | * Creates a {@link PriorityScheduler} using at most {@code concurrency} concurrent actions. 49 | * 50 | * Note: this does not ensure that the priorities will be adheared to exactly, as the 51 | * JVM's threading policy might allow one thread to dequeue an action, then let a second thread 52 | * dequeue the next action, run it, dequeue another, run it, etc. before the first thread runs 53 | * its action. It does however ensure that at the dequeue step, the thread will receive the 54 | * highest priority action available. 55 | */ 56 | public static PriorityScheduler withConcurrency(int concurrency) { 57 | return new PriorityScheduler(concurrency); 58 | } 59 | 60 | private PriorityScheduler(int concurrency) { 61 | this.executorService = Executors.newFixedThreadPool(concurrency); 62 | this.concurrency = concurrency; 63 | } 64 | 65 | /** 66 | * Prioritize {@link rx.functions.Action action}s with a numerical priority value. The higher 67 | * the priority, the sooner it will run. 68 | */ 69 | public Scheduler priority(final int priority) { 70 | return new InnerPriorityScheduler(priority); 71 | } 72 | 73 | private final class InnerPriorityScheduler extends Scheduler { 74 | 75 | private final int priority; 76 | 77 | private InnerPriorityScheduler(int priority) { 78 | this.priority = priority; 79 | } 80 | 81 | @Override 82 | public Worker createWorker() { 83 | synchronized (workerCount) { 84 | if (workerCount.get() < concurrency) { 85 | workerCount.incrementAndGet(); 86 | executorService.submit(new Runnable() { 87 | @Override 88 | public void run() { 89 | while (true) { 90 | try { 91 | ComparableAction action = queue.take(); 92 | action.call(); 93 | } catch (InterruptedException e) { 94 | Thread.currentThread().interrupt(); 95 | break; 96 | } 97 | } 98 | } 99 | }); 100 | } 101 | } 102 | return new PriorityWorker(queue, priority); 103 | } 104 | } 105 | 106 | private static final class PriorityWorker extends Worker { 107 | 108 | private final CompositeSubscription compositeSubscription = new CompositeSubscription(); 109 | private final PriorityBlockingQueue queue; 110 | private final int priority; 111 | 112 | private PriorityWorker(PriorityBlockingQueue queue, int priority) { 113 | this.queue = queue; 114 | this.priority = priority; 115 | } 116 | 117 | @Override 118 | public Subscription schedule(Action0 action) { 119 | return schedule(action, 0, MILLISECONDS); 120 | } 121 | 122 | /** 123 | * inspired by HandlerThreadScheduler.InnerHandlerThreadScheduler#schedule. 124 | * 125 | * @see InnerHandlerThreadScheduler 126 | */ 127 | @Override 128 | public Subscription schedule(Action0 action, long delayTime, TimeUnit unit) { 129 | final ComparableAction comparableAction = new ComparableAction(action, priority); 130 | 131 | final ScheduledAction scheduledAction = new ScheduledAction(comparableAction); 132 | scheduledAction.add(Subscriptions.create(new Action0() { 133 | @Override 134 | public void call() { 135 | queue.remove(comparableAction); 136 | } 137 | })); 138 | scheduledAction.addParent(compositeSubscription); 139 | compositeSubscription.add(scheduledAction); 140 | 141 | queue.offer(comparableAction, delayTime, unit); 142 | return scheduledAction; 143 | } 144 | 145 | @Override 146 | public void unsubscribe() { 147 | compositeSubscription.unsubscribe(); 148 | } 149 | 150 | @Override 151 | public boolean isUnsubscribed() { 152 | return compositeSubscription.isUnsubscribed(); 153 | } 154 | 155 | } 156 | 157 | private static final class ComparableAction implements Action0, Comparable { 158 | 159 | private final Action0 action; 160 | private final int priority; 161 | 162 | private ComparableAction(Action0 action, int priority) { 163 | this.action = action; 164 | this.priority = priority; 165 | } 166 | 167 | @Override 168 | public void call() { 169 | action.call(); 170 | } 171 | 172 | @Override 173 | public int compareTo(ComparableAction o) { 174 | return o.priority - priority; 175 | } 176 | } 177 | } 178 | -------------------------------------------------------------------------------- /src/test/java/me/ronshapiro/rx/priority/PrioritySchedulerTest.java: -------------------------------------------------------------------------------- 1 | package me.ronshapiro.rx.priority; 2 | 3 | import org.junit.Test; 4 | import org.junit.runner.RunWith; 5 | import org.junit.runners.JUnit4; 6 | 7 | import java.util.ArrayList; 8 | import java.util.Collections; 9 | import java.util.HashSet; 10 | import java.util.List; 11 | import java.util.Set; 12 | import java.util.concurrent.CountDownLatch; 13 | import java.util.concurrent.Executors; 14 | 15 | import rx.Observable; 16 | import rx.functions.Action1; 17 | import rx.schedulers.Schedulers; 18 | 19 | import static org.junit.Assert.fail; 20 | import static org.junit.Assert.assertEquals; 21 | 22 | @RunWith(JUnit4.class) 23 | public class PrioritySchedulerTest { 24 | 25 | @Test 26 | public void schedulesInOrderOfPriorityWhenSingleThreaded() throws Exception { 27 | final int parallelism = 1; 28 | PriorityScheduler scheduler = PriorityScheduler.withConcurrency(parallelism); 29 | 30 | final int count = 10000; 31 | final CountDownLatch finishLatch = new CountDownLatch(count); 32 | final CountDownLatch loopLatch = new CountDownLatch(1); 33 | final List actual = Collections.synchronizedList(new ArrayList()); 34 | final Object onNextLock = new Object(); 35 | 36 | for (int i = 0; i < count; i++) { 37 | Observable.just(i) 38 | .subscribeOn(scheduler.priority(i)) 39 | .subscribe(new Action1() { 40 | @Override 41 | public void call(Integer integer) { 42 | synchronized (onNextLock) { 43 | await(loopLatch); 44 | actual.add(integer); 45 | finishLatch.countDown(); 46 | } 47 | } 48 | }); 49 | } 50 | loopLatch.countDown(); 51 | finishLatch.await(); 52 | 53 | List subList = actual.subList(parallelism, actual.size()); 54 | int last = Integer.MAX_VALUE; 55 | for (int i : subList) { 56 | if (last < i) { 57 | fail("actual was not monotonically decreasing after the first N items, where N " + 58 | "is the scheduler's parallelism. failed at index " + actual.indexOf(i) + 59 | " (value = " + i + "). " + "Full list: " + actual); 60 | } 61 | last = i; 62 | } 63 | } 64 | 65 | @Test 66 | public void runsEachActionExactlyOnce_whenRunWithConcurrency() throws Exception { 67 | final int parallelism = 10; 68 | PriorityScheduler scheduler = PriorityScheduler.withConcurrency(parallelism); 69 | 70 | final int count = 10000; 71 | final CountDownLatch finishLatch = new CountDownLatch(count); 72 | final CountDownLatch loopLatch = new CountDownLatch(1); 73 | final Set actual = Collections.synchronizedSet(new HashSet()); 74 | final Object onNextLock = new Object(); 75 | 76 | for (int i = 0; i < count; i++) { 77 | Observable.just(i) 78 | .subscribeOn(scheduler.priority(i)) 79 | .subscribe(new Action1() { 80 | @Override 81 | public void call(Integer integer) { 82 | synchronized (onNextLock) { 83 | await(loopLatch); 84 | actual.add(integer); 85 | finishLatch.countDown(); 86 | } 87 | } 88 | }); 89 | } 90 | loopLatch.countDown(); 91 | finishLatch.await(); 92 | 93 | assertEquals(count, actual.size()); 94 | } 95 | 96 | 97 | private static void await(CountDownLatch latch) { 98 | try { 99 | latch.await(); 100 | } catch (InterruptedException e) { 101 | Thread.currentThread().interrupt(); 102 | } 103 | } 104 | } 105 | --------------------------------------------------------------------------------