title: Java Garbage Collector time limit
body: <h2>Situation</h2>
  
  <p>I am developing a client for a contest in Java, and whenever I receive a request, I have two seconds to respond. The time after the response until the next request is unknown.</p>
  
  <p>Sometimes, finding the right response takes nearly 2 seconds, and sometimes it's only a matter of a few milliseconds. The issue is when garbage collection happens in one of the longer calculations (which also allocates a lot of objects) right towards the end of the two seconds, and thus the response is sent too late and I get disqualified.</p>
  
  <p>Using verbose gc output I identified that the gc usually takes about 0.6s, even though I tried to limit it lower. I also tried to invoke <code>System.gc()</code> on the shorter calculations (since I am sure I have about 1.8s where I don't need to do anything), but it took 1-3s, which is not safe either.</p>
  
  <p>My program has very few long-living objects, most live shorter than a second.</p>
  
  <h2>Specs</h2>
  
  <p>I know that the program will always run on the same machine with these resources available:</p>
  
  <ul>
  <li>64 bit Ubuntu</li>
  <li>openjdk:8u151-jre</li>
  <li>one core of an <a href="https://ark.intel.com/products/92986/Intel-Xeon-Processor-E5-2620-v4-20M-Cache-2_10-GHz" rel="noreferrer">Intel® Xeon® Prozessor E5-2620 v4</a></li>
  <li>1.5 GB of RAM</li>
  </ul>
  
  <p>My current jvm parameters:</p>
  
  <pre><code>java -Dfile.encoding=UTF-8 \
    -XX:MaxGCPauseMillis=200 \
    -XX:GCPauseIntervalMillis=2050 \
    -XX:+UseConcMarkSweepGC -XX:+CMSParallelRemarkEnabled \
    -XX:+UseCMSInitiatingOccupancyOnly -XX:CMSInitiatingOccupancyFraction=70 \
    -XX:+ScavengeBeforeFullGC -XX:+CMSScavengeBeforeRemark \
    -verbose:gc -XX:+PrintGCDetails -XX:+PrintGCTimeStamps
  </code></pre>
  
  <h2>Ideas</h2>
  
  <ul>
  <li>Can I somehow tell the gc that it should collect some garbage now, but only for about 1.5 seconds?</li>
  <li>Is there a <code>System.gc()</code> equivalent that only works with the young objects and doesn't check the tenured generation?</li>
  <li>Can the jvm parameters be optimised to achieve better results?</li>
  </ul>