SHARE
TWEET

How to troll the JVM

DulcetAirman Nov 12th, 2013 (edited) 154 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. package ch.claude_martin.java8.security;
  2.  
  3. public class Troll {
  4.     volatile static Troll trash;
  5.     private final String msg;
  6.  
  7.     public Troll(final byte[] bytes) {
  8.         this.msg = new String(bytes);
  9.     }
  10.  
  11.     @Override
  12.     public String toString() {
  13.         return this.msg;
  14.     }
  15.  
  16.     @Override
  17.     protected void finalize() throws Throwable {
  18.         System.out.println("finalizing the object " + hashCode());
  19.         trash = this; // Don't mind me putting the reference there...
  20.     };
  21.  
  22.     public static void main(final String[] args) throws InterruptedException {
  23.         try {
  24.             Troll troll = new Troll(new byte[] { 85, 32, 109, 97, 100, 63 });
  25.             System.out.println("hash=" + troll.hashCode());
  26.             troll = null; // This hints the GC that "troll" can be collected
  27.         } catch (final Exception e) {
  28.         }
  29.         while (trash == null) {
  30.             System.gc(); // hint to run gc
  31.             Thread.sleep(100);
  32.             System.runFinalization(); // hint to run finalization
  33.             Thread.sleep(100);
  34.         }
  35.         System.out.println(trash);
  36.         System.out.println("hash=" + trash.hashCode());
  37.  
  38.     }
  39. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top