Fun with String.intern()

The intern() method in the String class is one of the lesser-known gems of the Java world. It’s quite subtle, brilliantly powerful, and potentially very dangerous. That having been said, it has long been one of my favourite bits of core Java API, mostly because it’s incredibly flexible in what it allows you to do.

What is intern()?

What does String.intern() actually do? It makes strings that look the same (ie: have the same content), into the same String object. For a more in-depth understanding, it’s worth going back to one of the most basic Java lessons: “Don’t use == on a String, use .equals”.

Console cmd = System.console();
String input = cmd.readLine("Enter Your Name: ");

if(input == "Henry") {
    // This will never ever be true

if(input.equals("Joe")) {
    // Well, this might be true

if(input.intern() == "Jeff") {
    // Surprise, this might also be true... just like .equals

Okay, so what’s going on here? The answer is that the == operator tests whether two primitives are the same, so it works for int, long, boolean, double and friends but it doesn’t appear to work for objects at first. This is because in Java, objects are all references so what you are testing is “is this object the same object as another object” rather than “does this object have the same data and fields as another object”. Put another way “are these two references pointing to the same memory location?”

Referencing Basics

The String.intern() method allows you to make use of the string constant-pool in the JVM. Every time you intern a String, it’s checked against the VM’s pool of Strings and you get a reference back that will always be the same for any given bit of contents. “Hello” will always == “Hello”, and so on. This internal pool of Strings is what causes this behaviour:

String string1 = "Hello";
String string2 = "Hello";
String string3 = new String("Hello");
String string4 = string3.intern();

assert string1 == string2; // true
assert string2 == string3; // false
assert string1 == string4; // true

When the Java compiler and VM encounter string1 and string2 they see that they have exactly the same content, and since String is an immutable type they’re turned into the same object under the hood. string3 is different, we used the new operator effectively forcing the VM to create a new object for us. string4 however asks the VM to use it’s string-pool by invoking the intern() method.

Getting Clever

You can use interned String references to massively speed-up configuration key lookup. If you declare the possible configuration properties as constant String objects in an interface, you can intern() the keys when they are loaded externally. This allows you to use an IdentityHashMap instead of a traditional HashMap.

public class Config {
    public static final String REMOTE_SERVER_ADDRESS = "remoteServer.address";

    private final Map config = new IdentityHashMap();

    public void load(Properties config) {
             .forEach((k) => config.put(k.intern(), config.getProperty(k)));

    public String get(final String key) {
        return config.get(key);

The above snippet will only ever work when the Config.get method is called with constants (static final) or other Strings that are interned.

Even more fun

Every field, method and class in Java has a name. It’s name (or identifier) is also stored in the same string-pool as the intern() method accesses. Meaning that there are some very strange things that start to happen with reflection:

public class Main {
        // this is true!
        Main.class.getMethod("main", String[].class).getName() == "main";


  1. Using String.intern might cause unexpected behaviour (ie: it can violate the principal or least astonishment), and make your code more confusing to your team-mates, most of us don’t expect to see identity-equality checks with Strings. If you are tempted to use it you should check with your team before doing so.
  2. Invoking intern is expensive in it’s own right, making it something to use with care. It’s fine when loading a configuration file on startup, it’s not something you want to do for ever equality check.
  3. The string-pool is a precious resource, and strings within it might not be garbage collected. For this reason you should never use intern on untrusted input.

Is Nashorn (JVM) faster than Node (V8)?

The answer to the question “Is Nashorn (JVM) faster than Node (V8)?” is in most people’s minds: a foregone conclusion, looking something like this expression.


It certainly was in my mind, until I actually ran a very simple benchmark that computes the Fibonacci sequence a few times (recursively). It’s a common enough benchmark, one frequently used to test method dispatching, recursion and maths in various languages / virtual machines. For disclosure, the code is listed below:

function fib(n) {
  if (n < 2)
    return 1;

try {
  print = console.log;
} catch(e) {

for(var n = 30; n <= 50; n++) {
  var startTime =;
  var returned = fib(n);
  var endTime =;
  print(n + " = " + returned + " in " + (endTime - startTime));

The results are, lets just say: “shocking”. The table below is both runs along side each other, the last numbers are the important ones: how many milliseconds each run took.

jason@Bender ~ $ node fib.js 
30 = 1346269 in 12
31 = 2178309 in 17
32 = 3524578 in 27
33 = 5702887 in 44
34 = 9227465 in 69
35 = 14930352 in 113
36 = 24157817 in 181
37 = 39088169 in 294
38 = 63245986 in 474
39 = 102334155 in 766
40 = 165580141 in 1229
41 = 267914296 in 2009
42 = 433494437 in 3241
43 = 701408733 in 5302
44 = 1134903170 in 8671
45 = 1836311903 in 13626
46 = 2971215073 in 22066
47 = 4807526976 in 45589
48 = 7778742049 in 74346
49 = 12586269025 in 120254
50 = 20365011074 in 199417
jason@Bender ~ $ jjs -ot fib.js 
30 = 1346269 in 70
31 = 2178309 in 16
32 = 3524578 in 19
33 = 5702887 in 30
34 = 9227465 in 48
35 = 14930352 in 76
36 = 24157817 in 123
37 = 39088169 in 197
38 = 63245986 in 318
39 = 102334155 in 517
40 = 165580141 in 835
41 = 267914296 in 1351
42 = 433494437 in 2185
43 = 701408733 in 3549
44 = 1134903170 in 5718
45 = 1836311903 in 9306
46 = 2971215073 in 15031
47 = 4807526976 in 34294
48 = 7778742049 in 38446
49 = 12586269025 in 61751
50 = 20365011074 in 100343

So what on earth is going on here? How can it be that the last result is 99 seconds faster on the Java VM than on V8, one of the fastest JavaScript engines on the planet?

The answer is actually hidden at the top of the tables: the -ot option being passed to JJS (Java JavaScript) is the key to this magic sauce. OT stands for Optimistic Typing, which aggressively assumes that variables are all compatible with the Java int type, and then falls back to more permissive types (like Object) when runtime errors happen. Because the code above only ever produces int values, this is a very good assumption to make and allows the Java VM to get on and optimise the code like crazy, where V8 continues to chug along with JavaScript’s Number type (actually it is more intelligent than that, but it’s just not showing in this little benchmark).

The point of this post is: don’t believe everything you read in benchmarks. They are very dependant on the code being run, and micro-benchmarks are especially dangerous things. The work that has been done on Optimistic Typing in Nashorn is amazing, and makes it a very attractive JavaScript environment. But you shouldn’t believe that just because these benchmarks show such a wide gap in performance that your Express application would run faster in Nashorn than under V8… In fact you’d be lucky to get it to run at all.

Feel free to replicate this experiment on your machine. It’s amazing to watch, it surprises me every time I re-run it.

Writing Express Middleware to Modify the Response

I recently had a need for some Express middleware that would track any change to a variable, and send the details of any changes in the response, but only if the response is JSON data. This turned out to be rather more interesting delve into ExpressJS than I expected, and I thought the details of it were worth a post detailing how to do it, and my findings.

The first thing you notice when writing Express middleware functions is that they take three arguments (I’m skipping error-handling middleware deliberately), the request, the response and a next() function that triggers the next step in the processing chain. The next function doesn’t typically take any arguments, instead you’re expected to modify the request and response objects to expose or capture any changes you want.

This post will show you how to capture any changes to a variable (we’re going to pretend all our users are playing a game and we have a leader-board), we want to track any changes that happen during the request and report both the changes and the current state of the variable in every response. I’m going to assume some other middleware has injected a user property onto the request. First off, this is what the code will look like:

const leaderboard = require('./leaderboard');
function leaderboardTracking(req, resp, next) {
  const user = req.user;
  const startingPosition = leaderboard.getUserPosition(user);
  const json_ = resp.json; // capture the default resp.json implementation

  resp.json = function(object) {
    const endPosition = leaderboard.getUserPosition(user);
    object['leaderboard_info'] = {
      'delta':    endPosition - startPosition,
      'position': endPosition,
      'score':    user.score
    };, object);


So in this example we swap out the json function with our own delegate implementation, but you’ll notice we leave the send function alone. The send function will delegate to the json function if it’s given a plain JavaScript object, and json in-turn uses send after stringifying the object.

You’ll also notice that the code doesn’t just invoke the captured json_ function, it uses the call function and specifies the response as this. The json function in Express expects to be invoked within the context of the response object, so we need to keep it that way.

That’s it really, it’s not a terribly complicated pattern, but it can be extremely powerful because it bounds the request / response cycle end-to-end.

BigDecimal and your Money


Theres more numbers in there than you think!


public void testScaleFactor() {
    final BigDecimal zero = new BigDecimal("0.0");
    final BigDecimal zerozero = new BigDecimal("0.00");

    assertEquals(zero, zerozero);

public void testScaleFactorCompare() {
    final BigDecimal zero = new BigDecimal("0.0");
    final BigDecimal zerozero = new BigDecimal("0.00");

    assertTrue(zero.compareTo(zerozero) == 0);


They’re true high precision structures.


public void testArithmatic() {
    BigDecimal value = new BigDecimal(1);
    value = value.divide(new BigDecimal(3));


try {
    return decimal1.divide(decimal2);
} catch(ArithmaticException ae) {


They don’t play nice with Databases.



CREATE TABLE transactions (
    initial_date DATETIME NOT NULL,
    effective_date DATETIME NOT NULL,
    description VARCHAR(30) NOT NULL,
    source_id BIGINT NOT NULL,
    destination_id BIGINT NOT NULL,
    in_amount BLOB NOT NULL,
    in_amount_currency CHAR(3) NOT NULL,
    effective_amount BLOB NOT NULL,
    effective_amount_currency CHAR(3) NOT NULL,
    charge_amount BLOB NOT NULL,
    tax_amount BLOB NOT NULL






A Cure to BigDecimal Woes:





6 Reasons to Develop Software on a MacBook Pro




Spotlight is Productivity Defined


It’s BSD Based Underneath



Gesture Recognizing Touch Pad




The Keyboard is Incredible



It’s Just Built Better





It Just Works


Android User Interface Development

Android User Interface Development: A Beginners Guide is the title of the book that I’ve been writing. The main reason I haven’t recently had a chance to update this blog. The book is not just about the basics of good user interface design, but also how exactly these principals can be applied on an Android device. The book takes the concepts and in a practical manor applies them directly to various parts of the Android developers stack.

In broad terms, the book covers the following aspects:

  • Designing user-friendly interfaces that support quick and easy access to information
  • Exploring and implement multiple layouts in Android to design user interfaces for the different screen sizes and densities
  • Ensuring a consistent user-interface experience and improve your application performance by reusing your application components
  • Designing easy-on-the-eye themes for your Android applications
  • Displaying and select complex data structures from applications such as an address-book or calendar application by using Android widgets
  • Animating visual queues of what the application is currently doing, and what effect their actions are having
  • Customizing the built-in classes in Android to enhance the user interface by creating tabs and galleries
  • Learning to Leverage Android’s resource loading system
  • Learning how best to present your user with information; or capture information from them

You can find more information about the book, and also pre-order yourself a copy from the Packt Publishing web-site.

Dear Google: Please Fork Java




