Java Puzzle 5: Ball

Mar 15, 2012

In today'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?

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++ < score++) {
                // The goal is to reach this line
                System.out.println("You cheated!");
            }
        }
    }

    public void play() throws Ball {
        throw ball;
    }
}

The same rules as usual apply; you must run with the security manager enabled (-Djava.security.manager). Your solution also must be in the play package. Putting anything else in the game package is not allowed.

If you found it, post your solution as a comment. These comments stay private, and become public later on the next blog post.