title: How does reflection and immutability supposed to work together
body: <p>According to <a href="http://download.oracle.com/otndocs/jcp/memory_model-1.0-pfd-spec-oth-JSpec/" rel="noreferrer">JSR-133</a> immutable objects are thread safe and don't need synchronization. However it's possible to update values of final fields using reflection:</p>
  
  <pre><code>package com.stackoverflow;
  
  import java.lang.reflect.Field;
  
  public class WhatsGoingOn {
  
      static class Immutable {
          private final int value;
  
          public Immutable(int value) {
              this.value = value;
          }
  
          public int getValue() {
              return value;
          }
      }
  
      public static void main(String[] args) throws NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException {
          final Immutable immutable = new Immutable(Integer.MIN_VALUE);
  
          final Field f = Immutable.class.getDeclaredField("value");
          f.setAccessible(true);
  
          System.out.println(immutable.getValue());
          f.set(immutable, Integer.MAX_VALUE);
          System.out.println(immutable.getValue());
      }
  }
  </code></pre>
  
  <p>Given number of frameworks (Spring and Hibernate are only a few) which rely on reflection I'm curious what does spec says about this scenario. E.g. if I put field update into synchronized block will that guarantee visibility in other threads, or value will be cached in registers as per spec for final.</p>
  
  <p><a href="http://download.oracle.com/otndocs/jcp/memory_model-1.0-pfd-spec-oth-JSpec/" rel="noreferrer">http://download.oracle.com/otndocs/jcp/memory_model-1.0-pfd-spec-oth-JSpec/</a></p>