title: Stream always empty—unless I give it time
body: <p>I have a little trouble understanding java streams. I created a JUnit test that basically stores an element in a database, retrieves it (results are returned in a stream), and then compares both elements. The test failed, so I started to debug. Suddenly the test passed. Turns out my breakpoint gave the stream the time it needed to build?!</p>
  
  <pre><code>@Test
  public void matchAllTest() {
      client.insert(object); //database schema is empty
  
      Stream&lt;Object&gt; stream = client.query("{ query matching all objects }");
  
      Object firstResult = stream.findFirst().get();
      assertObjectEquals(object, firstResult);
  }
  </code></pre>
  
  <p><code>query</code> works with Elasticsearch as a database and looks like this:</p>
  
  <pre><code>public Stream&lt;Object&gt; query(String query) {
      SearchRequestBuilder request = client.prepareSearch("index");
      request.setQuery(query);
  
      Stream.Builder&lt;Object&gt; stream = Stream.builder();
  
      SearchResponse response = request.get();
      SearchHits hits = response.getHits();
      hits.forEach(object -&gt; stream.accept(object);
  
      return stream.build();
  }
  </code></pre>
  
  <p><code>client</code> in the test refers to a class with the <code>query</code> method. <code>client</code> in the second code snippet refers to an Elasticsearch node client, see <a href="http://javadoc.kyubu.de/elasticsearch/HEAD/org/elasticsearch/client/Client.html" rel="nofollow">ES Java docs</a>.</p>
  
  <p>The test fails with a NoSuchElementException ("No value present")—unless I give it time.</p>
  
  <p>What exactly is happening here and how can I avoid an exception?</p>