OpenJDK and XKCD: Random number

OpenJDK and XKCD: Random number

A couple of days ago a our JPoint hackathon we discussed building (Adopt) OpenJDK. After finding out a better way to build OpenJDK on Windows (read it here), I’ve made my first improvement to OpenJDK.

This is a famous XKCD cartoon I wanted to implement:
getRandomNumber() { return 4; } // chosen by fair dice roll, guaranteed to be random

Where do we get started? Actually it turned out it is fairly easy to make this ‘improvement’. We just need to find the correct source file and do a build as described here.

Instead of the HotSpot core (which is all written in C) the JDK libraries are just classes/Java files. If you want to look at these Java files you’ll need to browse to [openjdk]/jdk/src/share/classes. There you’ll find familiar directories/packages like “java.*”, “javax.*” and even “sun.*”.

The file we need to change to improve Random is of course: [openjdk]/jdk/src/share/classes/java/util/Random.java

Now we browse until we find:

/**
 * Returns the next pseudorandom, uniformly distributed {@code int}
 * value from this random number generator's sequence. The general
 * contract of {@code nextInt} is that one {@code int} value is
 * pseudorandomly generated and returned. All 2<sup>32</sup> possible
 * {@code int} values are produced with (approximately) equal probability.
 *
 * <p>The method {@code nextInt} is implemented by class {@code Random}
 * as if by:
 *  <pre> {@code
 * public int nextInt() {
 *   return next(32);
 * }}</pre>
 *
 * @return the next pseudorandom, uniformly distributed {@code int}
 *         value from this random number generator's sequence
 */
public int nextInt() {
    return next(32);
}

Now we need fix the obvious error and turn it into:

/**
 * Returns guaranteed random number, rolled by nerdy DnD d20 dice.
 *
 * http://en.wikipedia.org/wiki/D20_System
 *
 * @return guaranteed random number
 */
public int nextInt() {
    return 14;
}

And after the build I pointed Eclipse to my newly generated JDK: [openjdk]/build/windows-x86_64-normal-server-release/images/j2sdk-image.
Next I run the following code:

import java.util.Random;

public class Test {

	public static void main(final String[] args) {
		final Random rnd = new Random();
		for(int i = 0; i < 10; i++) {
			System.out.println(rnd.nextInt());
		}
	}
}

Result:

14
14
14
14
14
14
14
14
14
14

Serious note:
This is absolutely not a valid patch but it really shows how easy it is to modify the JDK itself! There is a lot of low hanging fruit in the JDK, from missing unit tests, to unused imports to classes that don’t use generics yet. For more things to hack on, please read: https://java.net/projects/adoptopenjdk/pages/WhatToWorkOnForOpenJDK!