title: How do you make your Java application memory efficient?
body: <p>How do you optimize the heap size usage of an application that has a lot (millions) of long-lived objects? (big cache, loading lots of records from a db)</p>
  
  <ul>
  <li>Use the right data type
  
  <ul>
  <li>Avoid java.lang.String to represent other data types</li>
  </ul></li>
  <li>Avoid duplicated objects
  
  <ul>
  <li>Use enums if the values are known in advance</li>
  <li>Use object pools</li>
  <li>String.intern() (good idea?)</li>
  </ul></li>
  <li>Load/keep only the objects you need</li>
  </ul>
  
  <p>I am looking for general programming or Java specific answers. No funky compiler switch.</p>
  
  <p>Edit:</p>
  
  <p>Optimize the memory representation of a POJO that can appear millions of times in the heap.</p>
  
  <p>Use cases</p>
  
  <ul>
  <li>Load a huge csv file in memory (converted into POJOs)</li>
  <li>Use hibernate to retrieve million of records from a database</li>
  </ul>
  
  <p>Resume of answers:</p>
  
  <ul>
  <li>Use flyweight pattern</li>
  <li>Copy on write</li>
  <li>Instead of loading 10M objects with 3 properties, is it more efficient to have 3 arrays (or other data structure) of size 10M? (Could be a pain to manipulate data but if you are really short on memory...)</li>
  </ul>