DulcetAirman icon

How to troll the JVM

DulcetAirman | PRO | 11/12/13 01:47:59 PM UTC | 0 ⭐ | 857 👁️ | Never ⏰ | []
Java |

1.01 KB

|

None

|

0 👍

/

0 👎

package ch.claude_martin.java8.security;
 
public class Troll {
    volatile static Troll trash;
    private final String msg;
 
    public Troll(final byte[] bytes) {
        this.msg = new String(bytes);
    }
 
    @Override
    public String toString() {
        return this.msg;
    }
 
    @Override
    protected void finalize() throws Throwable {
        System.out.println("finalizing the object " + hashCode());
        trash = this; // Don't mind me putting the reference there...
    };
 
    public static void main(final String[] args) throws InterruptedException {
        try {
            Troll troll = new Troll(new byte[] { 85, 32, 109, 97, 100, 63 });
            System.out.println("hash=" + troll.hashCode());
            troll = null; // This hints the GC that "troll" can be collected
        } catch (final Exception e) {
        }
        while (trash == null) {
            System.gc(); // hint to run gc
            Thread.sleep(100);
            System.runFinalization(); // hint to run finalization
            Thread.sleep(100);
        }
        System.out.println(trash);
        System.out.println("hash=" + trash.hashCode());
 
    }
}

Comments