title: Under What Conditions Does ART Compact the Heap?
body: <p>One of the touted features of the ART runtime in Android 5.0+ is heap compaction, to reduce heap fragmentation. A fragmented heap can get <code>OutOfMemoryErrors</code> a lot easier, as there may not be a single contiguous free block of memory big enough for your needs, even if the heap overall has enough free space.</p>
  
  <p>I understand that this occurs when the app moves to the background, based on Google conference presentations and the like. However, the only statement that I can find on it in <a href="https://developer.android.com/studio/profile/investigate-ram.html#LogMessages" rel="noreferrer">the documentation</a> says:</p>
  
  <blockquote>
    <p>Homogeneous space compaction is free-list space to free-list space compaction which usually occurs when an app is moved to a pause imperceptible process state. The main reasons for doing this are reducing RAM usage and defragmenting the heap. </p>
  </blockquote>
  
  <p>It's unclear exactly what a "pause imperceptible process state" means, technically.</p>
  
  <p>Suppose an app does not have any foreground activities at the moment. Is there anything that the developer might have done that might prevent heap compaction for that app's process? For example, does having a foreground service block heap compaction?</p>