<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Wouter Coekaerts</title>
	<atom:link href="http://wouter.coekaerts.be/feed" rel="self" type="application/rss+xml" />
	<link>http://wouter.coekaerts.be</link>
	<description></description>
	<lastBuildDate>Tue, 01 May 2012 20:31:26 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
		<item>
		<title>Java Puzzle 6: Chicken or the Egg &#8211; Solution</title>
		<link>http://wouter.coekaerts.be/2012/puzzle-chicken-solution?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=puzzle-chicken-solution</link>
		<comments>http://wouter.coekaerts.be/2012/puzzle-chicken-solution#comments</comments>
		<pubDate>Mon, 26 Mar 2012 17:54:45 +0000</pubDate>
		<dc:creator>Wouter</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[puzzle]]></category>
		<category><![CDATA[solution]]></category>

		<guid isPermaLink="false">http://wouter.coekaerts.be/?p=545</guid>
		<description><![CDATA[Here&#8217;s the solution to the Chicken or the Egg puzzle. The constructor of Egg throws a NullPointerException if it&#8217;s not given a (non-null) Chicken, and vice versa for the Chicken constructor. So how can you get a reference to either of them? A common flaw that makes this possible (and even happen by accident) is [...]]]></description>
			<content:encoded><![CDATA[<p>Here&#8217;s the solution to the <a href="http://wouter.coekaerts.be/2012/puzzle-chicken">Chicken or the Egg puzzle</a>.</p>
<p>The constructor of <code>Egg</code> throws a <code>NullPointerException</code> if it&#8217;s not given a (non-null) <code>Chicken</code>, and vice versa for the <code>Chicken</code> constructor. So how can you get a reference to either of them?</p>
<p>A common flaw that makes this possible (and even happen by accident) is calling a method that can be overridden in a subclass from a constructor. But that&#8217;s not the case here. There&#8217;s one method you can override that the constructor doesn&#8217;t call, but Java calls eventually: <a href="http://docs.oracle.com/javase/6/docs/api/java/lang/Object.html#finalize()"><code>finalize()</code></a>. That method is called before an object is garbage collected, to give it a chance to clean up its resources. It is called even if the constructor threw an exception, so by overriding it we can get a reference to an egg that wasn&#8217;t fully created.</p>
<pre class="brush: java; title: ; notranslate">
package creator;

import chicken.Chicken;
import chicken.Egg;

public class Creator {
    static class FirstEgg extends Egg {
        FirstEgg() {
            super(null);
        }

        @Override
        protected void finalize() {
            new Chicken(this).ask();
        }
    }

    public static void main(String[] args) throws Exception {
        try {
            new FirstEgg();
        } catch (NullPointerException e) {
        }

        // there are ways to force garbage collection harder,
        // but this works good enough for me
        System.gc();
        System.runFinalization();
        Thread.sleep(1000);
    }
}
</pre>
<p>It&#8217;s well known that the finalization mechanism has <a href="https://www.securecoding.cert.org/confluence/display/java/OBJ11-J.+Be+wary+of+letting+constructors+throw+exceptions">several</a> <a href="http://www.javaspecialists.eu/archive/Issue170.html">problems</a>, and there are better <a href="http://java.sun.com/developer/technicalArticles/javase/finalization/">alternatives</a>. There are multiple ways to defend against this listed on the this <a href="https://www.securecoding.cert.org/confluence/display/java/OBJ11-J.+Be+wary+of+letting+constructors+throw+exceptions">secure coding standard for Java</a>. Another way is to throw the exception before calling the constructor from the <code>Object</code> class. That means doing the work <em>before</em> calling <code>super()</code> (or another constructor with <code>this()</code>). Since Java 6, this guarantees that <code>finalize()</code> won&#8217;t be called. For example here we dereference <code>mom.first</code> before calling <code>this(Object)</code> to ensure you cannot create an egg without a mommy: </p>
<pre class="brush: java; title: ; notranslate">
public class Egg {
    final Object first;

    public Egg(Chicken mom) {
        this(mom.first);
    }

    private Egg(Object first) {
        this.first = first;
    }
}
</pre>
<p>Congrats to the 17 people who found it. Matt Nathan was the first but it&#8217;s still a mystery if he&#8217;s a chicken, an egg or a <code>null</code>.</p>
<p>P.S.: The puzzles are taking a short vacation. They&#8217;ll continue in a few weeks.</p>
]]></content:encoded>
			<wfw:commentRss>http://wouter.coekaerts.be/2012/puzzle-chicken-solution/feed</wfw:commentRss>
		<slash:comments>18</slash:comments>
		</item>
		<item>
		<title>Java Puzzle 6: Chicken or the Egg</title>
		<link>http://wouter.coekaerts.be/2012/puzzle-chicken?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=puzzle-chicken</link>
		<comments>http://wouter.coekaerts.be/2012/puzzle-chicken#comments</comments>
		<pubDate>Thu, 22 Mar 2012 12:39:39 +0000</pubDate>
		<dc:creator>Wouter</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[puzzle]]></category>

		<guid isPermaLink="false">http://wouter.coekaerts.be/?p=537</guid>
		<description><![CDATA[Which was first, the chicken or the egg? What if every egg got the secret answer to that question imprinted from the chicken that laid it? And if then every chicken got that knowledge from the egg, passing it on from generation to generation. Then we could just ask any chicken! Now all you need [...]]]></description>
			<content:encoded><![CDATA[<p>Which was first, the chicken or the egg?</p>
<p>What if every egg got the secret answer to that question imprinted from the chicken that laid it?</p>
<pre class="brush: java; title: ; notranslate">
package chicken;

public class Egg {
    final Object first;

    public Egg(Chicken mom) {
        first = mom.first;
    }
}
</pre>
<p>And if then every chicken got that knowledge from the egg, passing it on from generation to generation. Then we could just ask any chicken!</p>
<pre class="brush: java; title: ; notranslate">
package chicken;

public class Chicken {
    final Object first;

    public Chicken(Egg egg) {
        first = egg.first;
    }

    public void ask() {
        // The goal is to reach this line
        System.out.println(&quot;First there was the &quot; + first);
    }
}
</pre>
<p>Now all you need to figure out is how to create the egg to create the chicken to create the egg to create chicken to ask the question.<br />
Here&#8217;s a naive attempt that will throw a <code>NullPointerException</code>. Can you edit it to make it work?</p>
<pre class="brush: java; title: ; notranslate">
package creator;

import chicken.Chicken;

public class Creator {
    public static void main(String[] args) {
        new Chicken(null).ask();
    }
}
</pre>
<p>The same <a href="http://wouter.coekaerts.be/puzzles">rules</a> and system as usual apply: you must run with the security manager enabled (<code>-Djava.security.manager</code>). Your solution must be in the <code>creator</code> package. If you found the solution, post it as a comment here below. These comments stay private, and become public later on the next blog post.</p>
<p>Good luck solving the mystery!</p>
]]></content:encoded>
			<wfw:commentRss>http://wouter.coekaerts.be/2012/puzzle-chicken/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Java Puzzle 5: Ball &#8211; Solution</title>
		<link>http://wouter.coekaerts.be/2012/puzzle-ball-solution?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=puzzle-ball-solution</link>
		<comments>http://wouter.coekaerts.be/2012/puzzle-ball-solution#comments</comments>
		<pubDate>Sun, 18 Mar 2012 22:27:05 +0000</pubDate>
		<dc:creator>Wouter</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[puzzle]]></category>
		<category><![CDATA[solution]]></category>

		<guid isPermaLink="false">http://wouter.coekaerts.be/?p=817</guid>
		<description><![CDATA[Cheating in the ball game was hard. Only three great Java minds managed to crack it: mihi, polygenelubricants and crazybob. As a reminder, here&#8217;s the puzzle: The approach If you couldn&#8217;t throw a ball, it wouldn&#8217;t be any fun. But extending Throwable also makes it implements Serializable, and that&#8217;s where the real fun starts. Using [...]]]></description>
			<content:encoded><![CDATA[<p>Cheating in the <a href="http://wouter.coekaerts.be/2012/puzzle-ball">ball game</a> was hard. Only three great Java minds managed to crack it: <a href="http://twitter.com/mihi42">mihi</a>, <a href="http://www.polygenelubricants.com/">polygenelubricants</a> and <a href="http://crazybob.org/">crazybob</a>.<br />
 As a reminder, here&#8217;s the puzzle:</p>
<pre class="brush: java; title: ; notranslate">
package game;

public final class Game {

    private final Ball ball = new Ball();
    private volatile long score;

    public final class Ball extends Throwable {
        private volatile long caught;

        private Ball() {
        }

        public synchronized void caught() {
            if (caught++ &lt; score++) {
                // The goal is to reach this line
                System.out.println(&quot;You cheated!&quot;);
            }
        }
    }

    public void play() throws Ball {
        throw ball;
    }
}
</pre>
<h2>The approach</h2>
<p>If you couldn&#8217;t <em>throw</em> a ball, it wouldn&#8217;t be any fun. But extending <code>Throwable</code> also makes it implements <code>Serializable</code>, and that&#8217;s where the real fun starts. Using serialization, we can create a ball that supposedly has been <code>caught</code> as many times as our serialized data claims.</p>
<p>The <code>Game</code> looks like it spoils the fun. You can&#8217;t throw it; but more importantly you can&#8217;t serialize it. If you try to naively serialize a ball directly, it will also try to serialize the game it is attached to, leading to a <code>NotSerializableException</code>.</p>
<p>Note that technically the reference from the ball to its game is just a field called something like <code>this$0</code>. With &#8220;attach&#8221; I mean assigning to that field. So this problem is equivalent to serializing an object that has a normal field that is not serializable.</p>
<p>The catch is that we don&#8217;t need to serialize the game and ball at all. We only need to <strong>de</strong>serialize the ball, and attach it to a <code>Game</code>. The <code>Game</code> instance doesn&#8217;t need to come directly from the serialized stream. We can put a substitute in its place, and override <code>readResolve</code> to replace it with a <code>Game</code> before it gets attached to the <code>Ball</code>.</p>
<h2>Cheating in practice</h2>
<p>There are multiple ways to create the raw data (byte array) that contains such a ball attached to a substitute game. Here&#8217;s mine; there are other ways in the comments below.<br />
We create a class <em>similar</em> to <code>Ball</code> (<code>Ba</code>). We give it the same <code>serialVersionUID</code> as <code>Ball</code> and our desired <code>caught</code> value. It&#8217;s attached to our substitute implementing <code>readResolve</code> (<code>Player</code>). We serialize that and replace just the name of the <code>Ba</code> class with the <code>Ball</code> class. Converting the <code>byte[]</code> to a <code>String</code> and back allows us to use <code>String.replace</code> for that.<br />
The name <code>Ba</code> is chosen so that <code>play.Player$Ba</code> has the same length as <code>game.Game$Ball</code>. Without that, directly replacing one with the other would corrupt the stream.</p>
<pre class="brush: java; title: ; notranslate">
package play;

import game.Game;
import game.Game.Ball;

import java.io.*;

public class Player implements Serializable {

    public static void main(String[] args) throws Exception {
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        new ObjectOutputStream(bos).writeObject(new Player().new Ba());
        byte[] bytes = new String(bos.toByteArray(), &quot;ISO-8859-1&quot;)
                .replace(&quot;play.Player$Ba&quot;, &quot;game.Game$Ball&quot;)
                .getBytes(&quot;ISO-8859-1&quot;);
        Ball ball = (Ball) new ObjectInputStream(new ByteArrayInputStream(bytes))
                .readObject();
        ball.caught();
    }

    class Ba implements Serializable {
        static final long serialVersionUID = -7172046060844866133L;

        private long caught = -1;
    }

    Object readResolve() {
        return new Game();
    }
}
</pre>
<p>This is what happens:</p>
<ul>
<li>When calling <code>readObject()</code>, first the <code>Ball</code> gets deserialized, and <code>caught</code> set to <code>-1</code>.</li>
<li>The value for <code>Ball.this$0</code> that gets deserialized is an instance of <code>Player</code>.</li>
<li>Before <code>Player</code> gets assigned to that field (which would fail, because it&#8217;s of the wrong type), its <code>readResolve</code> method is called, creating a new <code>Game</code> with <code>score</code> 0</li>
<li>That <code>Game</code> gets assigned to <code>Ball.this$0</code>, and <code>readObject()</code> returns the <code>Ball</code>.</li>
<li><code>ball.caught()</code> is called with <code>caught == -1</code> and <code>this$0.score == 0</code>, and you are caught cheating!</li>
</ul>
<h2>Conclusion</h2>
<p>Creating serializable objects that have a reference to a non-serializable object is a bad idea because you cannot serialize them. But with some dirty tricks, you can still deserialize them.</p>
<p>Java serialization is full of nasty unexpected possibilities. You could do a whole series of puzzles about just that. But if you&#8217;re really into that nastiness, all you need to do is look at the JDK security vulnerabilities over the last years.</p>
]]></content:encoded>
			<wfw:commentRss>http://wouter.coekaerts.be/2012/puzzle-ball-solution/feed</wfw:commentRss>
		<slash:comments>11</slash:comments>
		</item>
		<item>
		<title>Java Puzzle 5: Ball</title>
		<link>http://wouter.coekaerts.be/2012/puzzle-ball?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=puzzle-ball</link>
		<comments>http://wouter.coekaerts.be/2012/puzzle-ball#comments</comments>
		<pubDate>Thu, 15 Mar 2012 11:11:49 +0000</pubDate>
		<dc:creator>Wouter</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[puzzle]]></category>

		<guid isPermaLink="false">http://wouter.coekaerts.be/?p=799</guid>
		<description><![CDATA[In today&#8217;s Java puzzle we play a very simple game. I throw a ball, and if you catch it you score a point. Your total score is the amount of times you caught the ball. Or is there another way to score? The same rules as usual apply; you must run with the security manager [...]]]></description>
			<content:encoded><![CDATA[<p>In today&#8217;s Java puzzle we play a very simple game. I throw a ball, and if you catch it you score a point. Your total score is the amount of times you caught the ball. Or is there another way to score?</p>
<pre class="brush: java; title: ; notranslate">
package game;

public final class Game {

    private final Ball ball = new Ball();
    private volatile long score;

    public final class Ball extends Throwable {
        private volatile long caught;

        private Ball() {
        }

        public synchronized void caught() {
            if (caught++ &lt; score++) {
                // The goal is to reach this line
                System.out.println(&quot;You cheated!&quot;);
            }
        }
    }

    public void play() throws Ball {
        throw ball;
    }
}
</pre>
<p>The same <a href="http://wouter.coekaerts.be/puzzles">rules</a> as usual apply; you must run with the security manager enabled (<code>-Djava.security.manager</code>). Your solution also <em>must</em> be in the <code>play</code> package. Putting anything else in the <code>game</code> package is not allowed.</p>
<p>If you found it, post your solution as a comment. These comments stay private, and become public later on the next blog post.</p>
]]></content:encoded>
			<wfw:commentRss>http://wouter.coekaerts.be/2012/puzzle-ball/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Java Puzzle 4: Liquid</title>
		<link>http://wouter.coekaerts.be/2012/puzzle-liquid?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=puzzle-liquid</link>
		<comments>http://wouter.coekaerts.be/2012/puzzle-liquid#comments</comments>
		<pubDate>Thu, 08 Mar 2012 11:29:28 +0000</pubDate>
		<dc:creator>Wouter</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[puzzle]]></category>

		<guid isPermaLink="false">http://wouter.coekaerts.be/?p=687</guid>
		<description><![CDATA[Can you program your way past airport security? The usual rules apply. No liquids are allowed in your hand luggage: Can you, as a thirsty passenger, take some water with you anyways? Leave your answer in a comment. The comments will stay private for a while, and be published later in the next blog post.. [...]]]></description>
			<content:encoded><![CDATA[<p>Can you program your way past airport security? The usual <a href="http://wouter.coekaerts.be/puzzles">rules</a> apply.</p>
<p>No liquids are allowed in your hand luggage:</p>
<pre class="brush: java; title: ; notranslate">
package liquid;

import java.lang.String;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;

public class Luggage {
    private final Collection&lt;String&gt; items;

    public Luggage(Collection&lt;String&gt; items) {
        items = Collections.unmodifiableCollection(new ArrayList&lt;String&gt;(items));
        for (String item : items) {
            if (item.contains(&quot;liquid&quot;)) {
                throw new SecurityException(&quot;No liquids allowed in your hand luggage!&quot;);
            }
        }
        this.items = items;
    }

    public Collection&lt;String&gt; getItems() {
        return items;
    }

    public void fly() {
        if (items.contains(&quot;liquid water&quot;)) {
            // The goal is to reach this line
            System.out.println(&quot;Oh no, water on a plane! We're all going to die!&quot;);
        }
    }
}
</pre>
<p>Can you, as a thirsty passenger, take some water with you anyways? <del datetime="2012-03-08T12:50:01+00:00">Leave your answer in a comment. The comments will stay private for a while, and be published later in the next blog post.</del>. Try to solve it, and then look at the solutions in the comments below!</p>
<p><del datetime="2012-03-08T12:50:01+00:00">Update: comments were briefly not moderated, already showing the solution immediately; sorry for that.</del><br />
Update: Let&#8217;s try to do it differently from the other puzzles then! Only look at the comments below <b>after</b> you&#8217;re tried to solve it yourself!</p>
]]></content:encoded>
			<wfw:commentRss>http://wouter.coekaerts.be/2012/puzzle-liquid/feed</wfw:commentRss>
		<slash:comments>29</slash:comments>
		</item>
		<item>
		<title>Java Puzzle 3: Car &#8211; Solution</title>
		<link>http://wouter.coekaerts.be/2012/puzzle-car-solution?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=puzzle-car-solution</link>
		<comments>http://wouter.coekaerts.be/2012/puzzle-car-solution#comments</comments>
		<pubDate>Sun, 04 Mar 2012 16:37:47 +0000</pubDate>
		<dc:creator>Wouter</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[puzzle]]></category>
		<category><![CDATA[solution]]></category>

		<guid isPermaLink="false">http://wouter.coekaerts.be/?p=739</guid>
		<description><![CDATA[Let&#8217;s see how we can get the upgraded car to break the speed limit. Take a closer look at the car: Lesson to all you racers out there: We want the car to accelerate a lot (speed += acceleration must execute), but not do that thing where it hits the tree and comes to a [...]]]></description>
			<content:encoded><![CDATA[<p>Let&#8217;s see how we can get the <a href="http://wouter.coekaerts.be/2012/puzzle-car-2">upgraded car</a> to break the speed limit. Take a closer look at the car:</p>
<pre class="brush: java; title: ; notranslate">
package car;

public final class Car {
    private final int MAX_SPEED = 100;

    private int speed = 0;

    public synchronized void accelerate(int acceleration) {
        speed += acceleration;
        if (speed &gt; MAX_SPEED)
            crash();
    }

    public synchronized void crash() {
        speed = 0;
    }

    public synchronized void vroom() {
        if (speed &gt; MAX_SPEED * 10) {
            // The goal is to reach this line
            System.out.println(&quot;Vroom!&quot;);
        }
    }
}
</pre>
<p>Lesson to all you racers out there: We want the car to accelerate a lot (<code>speed += acceleration</code> must execute), but not do that thing where it hits the tree and comes to a full stop (<code>speed = 0</code> must not execute).</p>
<p>What can happen between those two statements? The <code>if (speed > MAX_SPEED)</code> doesn&#8217;t help us any further, because <code>speed</code> really needs to be higher than <code>MAX_SPEED</code>. So all that&#8217;s left is the call to the <code>crash()</code> method. That one has to fail: We want <code>crash()</code> to crash!</p>
<p>We can do that by making sure there&#8217;s not enough space left on the stack to be able to call any method. If the stack is <em>almost</em> full when we call <code>accelerate</code>, we get a <code>StackOverflowError</code> on the call to <code>crash()</code>. How do we get the stack to be <em>almost</em> full? One way is to just brute-force it: an infinitely recursing method that just keeps trying.</p>
<pre class="brush: java; title: ; notranslate">
package driver;

import car.Car;

public class Driver {
	private static Car car = new Car();

	public static void main(String args[]) {
		try {
			recurse();
		} catch (StackOverflowError e) {
		}

		car.vroom();
	}

	public static void recurse() {
		car.accelerate(1001);
		recurse();
	}
}
</pre>
<p>And that works!&#8230; On some systems at least. A problem here is that if you&#8217;re trying to accelerate so much and keep on crashing (after 1500 crashes on my system), the JVM does something no car maker ever would: it optimizes the car to ensure it can crash really fast. It in-lines the call to <code>crash()</code>, reducing it to essentially <code>if (speed > MAX_SPEED) speed = 0;</code>. That eliminates the possibility of a <code>StackOverflowError</code>.</p>
<p>We can work around that by being just a little gentler on the car: crash it a bit less, so the JVM doesn&#8217;t decide to optimise that. First grow the stack until it&#8217;s getting close to where it needs to be, and only then add the car into the equation. But the only way to know you&#8217;re getting close to the limit is by hitting it. Therefor we recurse without the car until we hit the stack overflow, then take a few steps back, and then apply the brute-forcing solution from above:</p>
<pre class="brush: java; title: ; notranslate">
package driver;

import car.Car;

public class Driver {
    static Car car = new Car();
    static int a = 0;

    public static void main(String args[]) {
        recurse();
        car.vroom();
    }

    static void recurse() {
        try {
            recurse(); // recurse without the car
        } catch (StackOverflowError e) {
            // when we've hit the limit of the stack, just go back out
        }
        if (a++ == 10) { // after taking 10 steps back
            recurse2(); // recurse with the car
        }
    }

    static void recurse2() {
        car.accelerate(1001);
        recurse2();
    }
}
</pre>
<p>An alternative solution is to use <a href="http://docs.oracle.com/javase/1.4.2/docs/api/java/lang/Thread.html#stop()">Thread.stop</a>. But it&#8217;s quite hard to time it right; it doesn&#8217;t work that reliable across systems. At first I expected it to be impossible in practice, but I was proven wrong. You can see the code in the comments below.<br />
You do need a special permission to call that method, but that&#8217;s one of the very few things included in the default security policy file. The only other permissions in there are opening listening sockets on high ports, and reading some standard system properties.</p>
<h2>Conclusion</h2>
<p>Not many succeeded in solving this one. The ones who did, and their solutions can be admired below as time-travelling comments that were posted before this blog post appeared.</p>
<p>The fact that this hack is possible makes me wonder. Is all privileged code in Java itself really prepared to crash at any time? Including all native code? If an applet makes the loading of a class fail in this way; does that cause <code>NoClassDefFoundError</code>s in other applets? How else could this be abused?&#8230;</p>
<p>Please, don&#8217;t try this at home. Car insurance usually doesn&#8217;t cover the failing of the crashing of the crash. Even if you first tried crashing without the car; running with your head straight into the tree. Blowing up the car right before it hits the tree is not appreciated either.</p>
<p>In the next puzzle we&#8217;ll sneak some goods passed airport security, so <a href="http://wouter.coekaerts.be/feed" title="feed">stay</a> <a href="http://twitter.com/WouterCoekaerts" title="twitter">tuned</a>!</p>
]]></content:encoded>
			<wfw:commentRss>http://wouter.coekaerts.be/2012/puzzle-car-solution/feed</wfw:commentRss>
		<slash:comments>37</slash:comments>
		</item>
		<item>
		<title>Java Puzzle 3: Car &#8211; Part 2</title>
		<link>http://wouter.coekaerts.be/2012/puzzle-car-2?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=puzzle-car-2</link>
		<comments>http://wouter.coekaerts.be/2012/puzzle-car-2#comments</comments>
		<pubDate>Sat, 03 Mar 2012 20:59:54 +0000</pubDate>
		<dc:creator>Wouter</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[puzzle]]></category>
		<category><![CDATA[solution]]></category>

		<guid isPermaLink="false">http://wouter.coekaerts.be/?p=572</guid>
		<description><![CDATA[Here&#8217;s the solution to the first part of the car puzzle. And, &#8212; for those who haven&#8217;t solved part one and seen it yet &#8212; we&#8217;ll toughen up the challenge for the second round. Here&#8217;s the method it&#8217;s all about: How do we make this go over the speed limit? The flaw is in the [...]]]></description>
			<content:encoded><![CDATA[<p>Here&#8217;s the solution to the <a href="http://wouter.coekaerts.be/2012/puzzle-car-1">first part of the car puzzle</a>. And, &#8212; for those who haven&#8217;t solved part one and seen it yet &#8212; we&#8217;ll toughen up the challenge for the second round. Here&#8217;s the method it&#8217;s all about:</p>
<pre class="brush: java; title: ; notranslate">
    public synchronized void accelerate(int acceleration) {
        if (acceleration &gt; MAX_SPEED - speed)
            crash();
        else
            speed += acceleration;
    }
</pre>
<p>How do we make this go over the speed limit?<br />
The flaw is in the check of the acceleration: it checks if it&#8217;s too high, but it forgot to check if it&#8217;s too low. Put your gearbox in reverse, push the pedal to the metal (<code>Integer.MIN_VALUE</code>), and the speedometer will wrap around.</p>
<pre class="brush: java; title: ; notranslate">
Car car = new Car();
car.accelerate(-1);
car.accelerate(Integer.MIN_VALUE);
car.vroom();
</pre>
<p>First we give it a little tap to set <code>speed</code> to <code>-1</code>. Then we push it all the way: the check if <code>Integer.MIN_VALUE > 99</code> passes, giving us <code>-1 + Integer.MIN_VALUE</code>. That causes an underflow, putting the car in its real top speed: <code>Integer.MAX_VALUE</code>.</p>
<p>Let&#8217;s avoid that kind of mistake, by checking the resulting speed instead of the acceleration:</p>
<pre class="brush: java; title: ; notranslate">
package car;

public final class Car {
    private final int MAX_SPEED = 100;

    private int speed = 0;

    public synchronized void accelerate(int acceleration) {
        speed += acceleration;
        if (speed &gt; MAX_SPEED)
            crash();
    }

    public synchronized void crash() {
        speed = 0;
    }

    public synchronized void vroom() {
        if (speed &gt; MAX_SPEED * 10) {
            // The goal is to reach this line
            System.out.println(&quot;Vroom!&quot;);
        }
    }
}
</pre>
<p>Can you still break the speed limit in this car?</p>
<p>The solutions (yes, that&#8217;s plural) to this are not always very reliable. How good they work may depend on the environment they&#8217;re running in. But with some tweaks and the right approach, it is possible to build a solution that should work all the time in practice without taking any significant time. 175 people solved the first part, but so far only 11 broke this part. If that doesn&#8217;t scare you off, good luck! You can try out your solution on <a href="http://puzzles.mooo.com/puzzles/car2">this ugly site</a>.</p>
<p>The <a href="http://wouter.coekaerts.be/2012/puzzle-car-solution">solutions</a> <del datetime="2012-03-04T17:14:24+00:00">will follow tomorrow</del> are available.</p>
]]></content:encoded>
			<wfw:commentRss>http://wouter.coekaerts.be/2012/puzzle-car-2/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Java Puzzle 3: Car</title>
		<link>http://wouter.coekaerts.be/2012/puzzle-car-1?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=puzzle-car-1</link>
		<comments>http://wouter.coekaerts.be/2012/puzzle-car-1#comments</comments>
		<pubDate>Thu, 01 Mar 2012 11:36:11 +0000</pubDate>
		<dc:creator>Wouter</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[puzzle]]></category>

		<guid isPermaLink="false">http://wouter.coekaerts.be/?p=564</guid>
		<description><![CDATA[This java puzzle comes in two parts. You have to solve this part to see the next one. To warm up the engine, we start with the easiest one. Part two will be harder. This car crashes if you accelerate too much. But can you make it go ten times faster than its limit? As [...]]]></description>
			<content:encoded><![CDATA[<p>This java puzzle comes in two parts. You have to solve this part to see the next one.<br />
To warm up the engine, we start with the easiest one. Part two will be harder.</p>
<p>This car crashes if you accelerate too much. But can you make it go ten times faster than its limit?</p>
<pre class="brush: java; title: ; notranslate">
package car;

public final class Car {
    private static final int MAX_SPEED = 100;

    private int speed = 0;

    public synchronized void accelerate(int acceleration) {
        if (acceleration &gt; MAX_SPEED - speed)
            crash();
        else
            speed += acceleration;
    }

    public synchronized void crash() {
        speed = 0;
    }

    public synchronized void vroom() {
        if (speed &gt; MAX_SPEED * 10) {
            // The goal is to reach this line
            System.out.println(&quot;Vroom!&quot;);
        }
    }
}
</pre>
<p>As a driver, do what needs to be done to push the car over its limit. Anything in your code is allowed; any trick outside the code is not. You must run with <code>-Djava.security.manager</code>, so <code>setAccessible</code> won&#8217;t work. If in doubt, read <a href="http://wouter.coekaerts.be/puzzles">the exact rules</a>.</p>
<pre class="brush: java; title: ; notranslate">
package driver;

import car.Car;

public class Driver {
    public static void main(String args[]) {
        // TODO break the speed limit
        Car car = new Car();
        car.accelerate(1001);
        car.vroom();
    }
}
</pre>
<p>If you&#8217;ve found the solution, post it into <a href="http://puzzles.mooo.com/puzzles/car1">the ugly form over there</a>. There it will be compiled and ran, and if it works, you will be directed to part two.</p>
<p>To be notified of when the solution and next puzzles come out, follow the <a href="http://wouter.coekaerts.be/feed">rss feed</a> or <a href="https://twitter.com/WouterCoekaerts">twitter</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://wouter.coekaerts.be/2012/puzzle-car-1/feed</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>Java Puzzle 2: Dreams &#8211; Solution</title>
		<link>http://wouter.coekaerts.be/2012/puzzle-dreams-solution?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=puzzle-dreams-solution</link>
		<comments>http://wouter.coekaerts.be/2012/puzzle-dreams-solution#comments</comments>
		<pubDate>Sun, 26 Feb 2012 16:05:13 +0000</pubDate>
		<dc:creator>Wouter</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[puzzle]]></category>
		<category><![CDATA[solution]]></category>

		<guid isPermaLink="false">http://wouter.coekaerts.be/?p=506</guid>
		<description><![CDATA[Time to dream the solution to the dreams puzzle. As a reminder, here&#8217;s the challenge: Solution The synchronized on the dream method means that it takes the monitor (lock) of the Sleeper object when we enter it, and it releases it again when we leave it. No other thread can enter the method while the [...]]]></description>
			<content:encoded><![CDATA[<p>Time to dream the solution to the <a href="http://wouter.coekaerts.be/2012/puzzle-dreams">dreams puzzle</a>. As a reminder, here&#8217;s the challenge:</p>
<pre class="brush: java; title: ; notranslate">
package sleep;

import dream.Dream;

public class Sleeper {
	private int level;

	public synchronized int enter(Dream dream) {
		level++;
		try {
			dream.dream(this);
		} finally {
			level--;
		}
		return level;
	}
}
</pre>
<pre class="brush: java; title: ; notranslate">
package sleep;

import dream.Dream;

public class Main {
	public static void main(String[] args) {
		if (new Sleeper().enter(new Dream()) != 0) {
			// The goal is to reach this line
			System.out.println(&quot;Am I still dreaming?&quot;);
		}
	}
}
</pre>
<h2>Solution</h2>
<p>The <code>synchronized</code> on the <code>dream</code> method means that it takes the monitor (lock) of the Sleeper object when we enter it, and it releases it again when we leave it. No other thread can enter the method while the monitor is held.</p>
<p>But here&#8217;s the catch: the monitor isn&#8217;t necessarily held <em>all</em> the time while the method is running. With <a href="http://docs.oracle.com/javase/6/docs/api/java/lang/Object.html#wait(long)"><code>Object.wait</code></a> you can release a monitor in the middle of a <code>synchronized</code> method.</p>
<p>How do we apply that to solve this puzzle? When we enter the outer dream, we use <code>wait</code> to release the monitor. But first we launch a separate thread, that will also enter a dream. Entering that inner dream makes the second thread take the monitor. So in the inner dream, we use <code>wait</code> a second time to release the monitor. That allows the main thread stop waiting, take the monitor back, and leave the outer dream. And there we are: we have woken up from the outer dream, back where we started in <code>main</code>, but the dream within the dream goes on in the second thread.</p>
<pre class="brush: java; title: ; notranslate">
package dream;

import sleep.Sleeper;

public class Dream {
	private static void doWait(Sleeper s) {
		try {
			s.wait(200);
		} catch (InterruptedException e) {
		}
	}

	public void dream(final Sleeper s) {
		new Thread() {
			public void run() {
				s.enter(new Dream() {
					@Override
					public void dream(Sleeper s) {
						doWait(s);
					}
				});
			}
		}.start();

		doWait(s);
	}
}
</pre>
<p><img src="/files/puzzles/dreams-solution.png" /></p>
<h2>And the winner is&#8230;</h2>
<p>I got more answers than I expected. The first one came from <a href="http://www.jroller.com/ethdsy/">David Shay</a>. Congrats!</p>
<p>It&#8217;s a bit repetitive, but as promised, you can see and compare all dreams as comments below this post.</p>
<h2>Conclusion</h2>
<p>The moral of the story: <code>synchronized</code> on a method doesn&#8217;t mean two different threads can&#8217;t be in it at the same time. It only ensures that such threads cannot execute concurrently; at least one of them must be waiting.</p>
<p>You can prevent this kind of abuse and other problems, by using a private object as monitor:</p>
<pre class="brush: java; title: ; notranslate">
public class Sleeper {
	private final Object lock = new Object();

	public int dream(Dream dream) {
		synchronized(lock) {
			...
		}
	}
}
</pre>
<p>But that still leaves me unsure if I actually woke up this morning.</p>
]]></content:encoded>
			<wfw:commentRss>http://wouter.coekaerts.be/2012/puzzle-dreams-solution/feed</wfw:commentRss>
		<slash:comments>150</slash:comments>
		</item>
		<item>
		<title>Java Puzzle 2: Dreams</title>
		<link>http://wouter.coekaerts.be/2012/puzzle-dreams?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=puzzle-dreams</link>
		<comments>http://wouter.coekaerts.be/2012/puzzle-dreams#comments</comments>
		<pubDate>Thu, 23 Feb 2012 11:27:40 +0000</pubDate>
		<dc:creator>Wouter</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[puzzle]]></category>

		<guid isPermaLink="false">http://wouter.coekaerts.be/?p=496</guid>
		<description><![CDATA[Here&#8217;s another challenging Java Puzzle! The same rules as for the clowns puzzle apply. [Update: In short: anything in your code is allowed; any trick outside the code is not. You must run with -Djava.security.manager, so setAccessible won't work.]. We&#8217;ve learned our lesson from the clowns: There are no hidden calls behind the scenes here, [...]]]></description>
			<content:encoded><![CDATA[<p>Here&#8217;s another challenging Java Puzzle! The <a href="http://wouter.coekaerts.be/puzzles">same rules</a> as for the <a href=" http://wouter.coekaerts.be/2012/puzzle-clowns">clowns puzzle</a> apply. [Update: In short: anything in your code is allowed; any trick outside the code is not. You must run with <code>-Djava.security.manager</code>, so <code>setAccessible</code> won't work.].</p>
<p>We&#8217;ve learned our lesson from the clowns: There are no hidden calls behind the scenes here, and we embrace recursion; we count on it.</p>
<p>Have you ever woken up from a dream, to then discover that you&#8217;re actually still dreaming? If you then wake up, how do you know you&#8217;re back in reality? This puzzle implements a solution to that problem: you count the recursion level of your dreams as you enter and exit them:</p>
<pre class="brush: java; title: ; notranslate">
package sleep;

import dream.Dream;

public class Sleeper {
	private int level;

	public synchronized int enter(Dream dream) {
		level++;
		try {
			dream.dream(this);
		} finally {
			level--;
		}
		return level;
	}
}
</pre>
<p>A sleeper starts sleeping and enters a dream (level one). He can have a dream within that dream, and even enter deeper dreaming levels. But when he leaves the outer dream, he&#8217;s awake again, so he should be at level zero again, right?</p>
<pre class="brush: java; title: ; notranslate">
package sleep;

import dream.Dream;

public class Main {
	public static void main(String[] args) {
		if (new Sleeper().enter(new Dream()) != 0) {
			// The goal is to reach this line
			System.out.println(&quot;Am I still dreaming?&quot;);
		}
	}
}
</pre>
<p>The counting of the levels looks really safe, so this seems impossible:<br />
<img src="http://wouter.coekaerts.be/files/puzzles/inception-totem.jpg" alt="" class="alignright"></p>
<ul>
<li>Every time you enter a dream <code>level</code> is increased. Because of the <code>finally</code> block, there&#8217;s no way to leave a dream without decreasing it again.</li>
<li>The <code>synchronized</code> block makes sure no other thread can call it concurrently. The level is returned from the dream method to make sure it&#8217;s read within the <code>synchronized</code> block.</li>
<li><code>dream</code> is the very first thing that&#8217;s called on the <code>Sleeper</code>, so the level must be zero when entering it. The value that&#8217;s returned from it must be zero too then, because even if we call it recursively we must enter as many dreams as we exit.</li>
</ul>
<pre class="brush: java; title: ; notranslate">
// this is the only file you're allowed to edit
package dream;

import sleep.Sleeper;

public class Dream {
	public void dream(Sleeper s) {
		// TODO implement me
	}
}
</pre>
<p>Do you eat Java, breathe Java, and even dream in Java? Can you find the flaw in this reasoning? Can you imagine a really weird dream, that would make the sleeper lose count? <del datetime="2012-02-27T11:53:11+00:00">If so, leave your code in a comment here!</del></p>
<p>To give everyone a fair chance, those comments <del datetime="2012-02-27T11:53:11+00:00">will stay</del> were hidden for a while. They <del datetime="2012-02-26T16:17:43+00:00">will become public soon</del> are now public, together with a <a href="http://wouter.coekaerts.be/2012/puzzle-dreams-solution">follow-up blog post</a>.<br />
To be notified of that and the next puzzles, follow the <a href="http://wouter.coekaerts.be/feed">feed</a> or <a href="https://twitter.com/WouterCoekaerts">twitter</a>.</p>
<p>PS: This puzzle is appearing simultaneously in the <a href="http://www.javaspecialists.eu/archive/Issue199.html">Java Specialists&#8217; Newsletter</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://wouter.coekaerts.be/2012/puzzle-dreams/feed</wfw:commentRss>
		<slash:comments>8</slash:comments>
		</item>
	</channel>
</rss>

