title: EJB and static fields
body: <p>I would like to have a static read only collection in a stateless session bean. Ideally it will only be initialized once and available to bean instances as long as the application is running.</p>
  
  <p>Let's assume that this application is deployed in a clustered environment with multiple servers/JVMs. </p>
  
  <p>As I understand it, in the first case, the static variable barList gets initialized at the same time when the bean is created by the container and lives as long as the bean (or maybe even longer?) and there's no danger of it being garbage collected while the bean instance is alive.</p>
  
  <p>In the second case, barList gets initialized when the Foo class gets loaded which is when the bean's getBarList() method gets executed. What happens when it's returned though? Will it be destroyed after the bean method is done executing?</p>
  
  <p>Case 1: </p>
  
  <pre><code>@Stateless
  public class MrBean implements BeanInterface{
  
  private static final List&lt;Bar&gt; barList;
  
  static{
  
  barList = new ArrayList&lt;Bar&gt;();
  
  //create some bars, add them to the list
  
  }
  
  public List&lt;Bar&gt; getBarList(){
  
      return barList;
  }
  }
  </code></pre>
  
  <p>Case 2:</p>
  
  <pre><code>@Stateless
  public class MrBean implements BeanInterface{
  
  public List&lt;Bar&gt; getBarList (){
  
  return Foo.barList;
  
  }
  
  }
  
  public class Foo {
  
  public static final List&lt;Bar&gt; barList;
  
  static{ 
  
  barList = new ArrayList&lt;Bar&gt;();
  
  // create bars, add them to barList 
  
  }
  
  }
  </code></pre>