fork download
  1. /* package whatever; // don't place package name! */
  2.  
  3.  
  4. import sun.misc.Unsafe;
  5. import java.lang.reflect.Field;
  6.  
  7. /* Name of the class has to be "Main" only if the class is public. */
  8. class Ideone
  9. {
  10.  
  11. private static final Unsafe theUnsafe;
  12. static {
  13. try {
  14. Field f = Unsafe.class.getDeclaredField("theUnsafe");
  15. f.setAccessible(true);
  16. theUnsafe = (Unsafe) f.get(null);
  17. } catch (ReflectiveOperationException roe) {
  18. }
  19. }
  20.  
  21. public static void setStaticObjectUnsafe(final Field field, Object value) {
  22. final Object staticFieldBase = theUnsafe.staticFieldBase(field);
  23. final long staticFieldOffset = theUnsafe.staticFieldOffset(field);
  24. theUnsafe.putObject(staticFieldBase, staticFieldOffset, value);
  25. }
  26.  
  27. // Integer, not int, so javac won't inline it.
  28. static final Integer VALUE = 10;
  29.  
  30. static Integer useField() {
  31. for (int i = 0; i < 1_000_000; i++) {
  32. if (VALUE != 10) {
  33. return VALUE;
  34. }
  35. }
  36. return VALUE;
  37. }
  38.  
  39. public static void main (String[] args) throws Exception
  40. {
  41. useField();
  42. useField();
  43. setStaticObjectUnsafe(Ideone.class.getDeclaredField("VALUE"), 100);
  44. System.out.println(useField());
  45. }
  46. }
Success #stdin #stdout 0.1s 51832KB
stdin
Standard input is empty
stdout
10