title: How to specify the exact execution order of asynchronous calls in Scala unit tests?
body: <p>I have written many different unit tests for futures in Scala.
  All asynchronous calls use an execution context.
  To make sure that the asynchronous calls are always executed in the same order, I need to delay some tasks which is rather difficult and slows the tests down.
  The executor might still (depending on its implementation) complete some tasks before others.</p>
  
  <p>What is the best way to test concurrent code with a specific execution order? For example, I have the following test case:</p>
  
  <pre><code>"firstSucc" should "complete the final future with the first one" in {
      val executor = getExecutor
      val util = getUtil
      val f0 = util.async(executor, () =&gt; 10)
      f0.sync
      val f1 = util.async(executor, () =&gt; { delay(); 11 })
      val f = f0.firstSucc(f1)
      f.get should be(10)
    }
  </code></pre>
  
  <p>where delay is <code>def delay() = Thread.sleep(4000)</code> and <code>sync</code> synchronizes the future (calls <code>Await.ready(future, Duration.Inf)</code>).
  That's how I want to make sure that f0 is already completed and f1 completes AFTER f0. It is not enough that f0 is completed since <code>firstSucc</code> could be shuffling the futures. Therefore, f1 should be delayed until after the check of <code>f.get</code>.</p>
  
  <p>Another idea is to create futures from promises and complete them at a certain point in time:</p>
  
  <pre><code>  "firstSucc" should "complete the final future with the first one" in {
      val executor = getExecutor
      val util = getUtil
      val f0 = util.async(executor, () =&gt; 10)
      val p = getPromise
      val f1 = p.future
      val f = f0.firstSucc(f1)
      f.get should be(10)
      p.trySuccess(11)
    }
  </code></pre>
  
  <p>Is there any easier/better approach to define the execution order? Maybe another execution service where one can configure the order of submitted tasks?
  For this specific case it might be enough to delay the second future until after the result has been checked but in some cases ALL futures have to be completed but in a certain order.</p>
  
  <p>The complete code can be found here: <a href="https://github.com/tdauth/scala-futures-promises" rel="nofollow noreferrer">https://github.com/tdauth/scala-futures-promises</a></p>
  
  <p>The test case is part of this class: <a href="https://github.com/tdauth/scala-futures-promises/blob/master/src/test/scala/tdauth/futuresandpromises/AbstractFutureTest.scala" rel="nofollow noreferrer">https://github.com/tdauth/scala-futures-promises/blob/master/src/test/scala/tdauth/futuresandpromises/AbstractFutureTest.scala</a></p>
  
  <p>This question might be related since Scala can use Java Executor Services: <a href="https://stackoverflow.com/questions/2153663/controlling-task-execution-order-with-executorservice">Controlling Task execution order with ExecutorService</a></p>