My Solution to Wouter Coekaerts’ Clown Puzzle

Wouter Coekaerts has published some really nice Java puzzles in his site. This is my solution to the first one. My solution is not as simple and elegant as his, but hey – it works:

package you;

import clowns.Clown;
import clowns.Volkswagen;

public class You {

	static final Volkswagen vw = new Volkswagen();

	public static void main(String args[]) throws InterruptedException {

		for (int i = 0; i < 20; i++) {

			new Thread() {
				@Override
				public void run() {
					vw.add(new MyClown());
				}
			}.start();
		}

		// I'm an ugly hack
		Thread.sleep(5000);

		synchronized (vw) {
			vw.notifyAll();
		}

		// Me too!
		Thread.sleep(5000);

		vw.done();
	}

	private static class MyClown extends Clown {

		@Override
		public int hashCode() {
			try {
				vw.wait();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			return super.hashCode();
		}
	}
}

My solution took advantage of the fact that using a synchronized method instead of synchronizing on a private lock object gives an attacker to ability to manipulate the Volkswagen’s locking mechanism from the outside. Had the programmer used a private object for synchronization, my solution wouldn’t have worked (which is another reason why Wouter’s solution is superior).

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s