Disgruntled Bomb: Java Edition

Zunächst ein bisschen Hintergrund:

If p is a value of type int, then boxing conversion converts p into a reference r of class and type Integer, such that r.intValue() == p

Ideally, boxing a given primitive value p, would always yield an identical reference. In practice, this may not be feasible using existing implementation techniques. The rules above are a pragmatic compromise. The final clause above requires that certain common values always be boxed into indistinguishable objects. The implementation may cache these, lazily or eagerly.

So, und jetzt einen Thread starten, der im Hintergrund sich diese cached, boxed Integers holt und modifiziert, etwa so:

package dont.try_this.at_home;
import java.lang.*;

class ValueMunger extends Thread {
    public void run() {
        while(true) {
            try { sleep(1000); } catch (Throwable t) { }

    public void munge() {
        try {
            Field field = Integer.class.getDeclaredField( "value" );
            field.setAccessible( true );
            for(int i = -127; i<=128; i++)
                // either the same (90%), +1 (10%), or 42 (1%)
                Math.random() < 0.9 ? i : Math.random() < 0.1 ? 42 : i+1  );
        } catch (Throwable t) { ; }


Jetzt irgendwo ein <strong>new ValueMunger()).start();</strong> einbauen, und schon geht der Spass los:

Integer a = 2;
Integer b = 3;

System.out.println( a + b ); // could be 5, 6, 7, 44, 45, or 84

Ist das nicht nett?
Viel spass beim Debuggen…

Short URL for this post: https://blog.oio.de/RwpMb
This entry was posted in Did you know?, Java Basics and tagged . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *