title: How to avoid memory overflow using high throughput JAVA I/O Stream from JDBC connectors?
body: <p>Consider the task of fetching a limited amount of data from a (w.r.t memory) infinite source, e.g. I need to fetch <code>counts</code> from an huge table consisting of billions and more entries, labeled by <code>timestamp</code> and <code>foreign_key</code> within a finite but possibly huge time window. But for later consumption I only need maximally <code>gridSize</code> values.</p>
  
  <p>Note:
  The backing DB is a MariaDb and we use spring data jpa to connect to the database.</p>
  
  <p>One stream based approach is:</p>
  
  <pre><code>int stepSize = (int) (numberOfCountsInWindow / gridSize) + 1;
  
  StreamUtils
       .zipWithIndex(countStream)
       .filter(countIndexed -&gt; countIndexed.getIndex() % stepSize == 0)
          ...
          &lt;intermediate steps&gt;
          ...
       .collect(Collectors.toList())
  </code></pre>
  
  <p>I've tried plenty of others, like:</p>
  
  <ul>
  <li>a custom <code>Collector</code>, that uses an <code>AtromicLong</code> to decide if the next value is added to the final list or just ignored,</li>
  <li>Flux.defere( () -> ), to use the Flux back-pressure management</li>
  <li>Java 11</li>
  <li>plenty of MySQL options like "useCursorFetch=true" in combination with a finite prefetch size as <code>@QueryHint()</code></li>
  <li>...</li>
  </ul>
  
  <p>However, all of what I've tried leads to <code>GC overhead limit exceeded</code> (with the heap size limited to 2048, which is the default for our applications).</p>
  
  <p>The reason is, the cpu is totally busy garbage collecting, while the memory consumption is just filling up until finally the application crashes.</p>
  
  <p>What I actually expected (or at least hoped for), was the stream to "realize" the filtering and just continue with the actual computing, at best using 100% cpu, and the garbage collector to easily remove the unused objects, since they are filtered out anyway and don't even need to be parsed (was hoping for the laziness of the stream to help here). However, this doesn't seem to work as I was hoping for.</p>
  
  <p>Comments or suggestions are very welcome, since I'd like to (at least) understand (at best solve) rather then just accept the situation.</p>
  
  <p>EDIT: Alternatives to MariaDB (maybe Cassandra?) are also welcome.</p>