Java memes which refuse to die

Also titled; My pet hates in Java coding. 

There are a number of Java memes which annoy me, partly because they were always a bad idea, but mostly because people still keep picking them up years after there is better alternatives.

Using StringBuffer instead of StringBuilder

The Javadoc for StringBuffer from 2004 states

As of release JDK 5, this class has been supplemented with an equivalent class designed for use by a single thread, StringBuilder. The StringBuilder class should generally be used in preference to this one, as it supports all of the same operations but it is faster, as it performs no synchronization. 

Not only is StringBuilder a better choice, the occasions where you could have used a synchronized StringBuffer are so rare, its unlike it was ever a good idea.

Say you had the code

// run in two threads
sb.append(key).append("=").append(value).append(", ");

Each append is thread safe, but the lock could be release at any point meaning you could get

key1=value1, key2=value2, 
key1=key2value1=, value2, 
key1key2==value1value2, , 

What makes it worse is that the JIT and JVM will attempt to hold onto the lock between calls in the interests of efficiency. This means you can have code which passes all your tests and works in production for years, but then very rarely breaks, possibly due to upgrading your JVM.

Using DataInputStream to read text

Another common meme is using DataInputStream when reading text in the following template (three lines with the two readers on the same line) I suspect there is one original code which gets copied around.

FileInputStream fstream = new FileInputStream("filename.txt");  
DataInputStream in = new DataInputStream(fstream);  
BufferedReader br = new BufferedReader(new InputStreamReader(in));  

This is bad for three reasons

  • You might be tempted to use in to read binary which won’t work due to the buffered nature of BufferedReader. (I have seen this tried)
  • Similarly, you might believe that DataInputStream does something useful here when it doesn’t
  • There is a much shorter way which is correct.
BufferedReader br = new BufferedReader(new FileReader("filename.txt")); 
// or with Java 7.
try (BufferedReader br = new BufferedReader(new FileReader("filename.txt")) {
    // use br
}

Using Double Checked Locking to create a Singleton

When Double checked locking was first used it was a bad idea because the JVM didn’t support this operation safely.

// Singleton with double-checked locking:
public class Singleton {
    private volatile static Singleton instance;

    private Singleton() { }

    public static Singleton getInstance() {
        if (instance == null) {
            synchronized (Singleton.class) {
                if (instance == null) {
                    instance = new Singleton();
                }
            }
        }
        return instance;
    }
}

The problem was that until Java 5.0, this usually worked but wasn’t guaranteed in the memory model. There was a simpler option which was safe and didn’t require explicit locking.

// suggested by Bill Pugh
public class Singleton {
    // Private constructor prevents instantiation from other classes
    private Singleton() { }

    /**
     * SingletonHolder is loaded on the first execution of Singleton.getInstance()
     * or the first access to SingletonHolder.INSTANCE, not before.
     */
    private static class SingletonHolder {
        public static final Singleton INSTANCE = new Singleton();
    }

    public static Singleton getInstance() {
        return SingletonHolder.INSTANCE;
    }
}

This was still verbose, but it worked and didn’t require an explicit lock so it could be faster.

In Java 5.0, when they fixed the memory model to handle double locking safely, they also introduced enums which gave you a much simpler solution.

In the second edition of his book Effective Java, Joshua Bloch claims that “a single-element enum type is the best way to implement a singleton” 

With an enum, the code looks like this.

public enum Singleton {
    INSTANCE;
}

This is lazy loaded, thread safe, without explicit locks and much simpler.

Reference: Java memes which refuse to die from our JCG partner Peter Lawrey at the Vanilla Java blog.

Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you two of our best selling eBooks for FREE!

JPA Mini Book

Learn how to leverage the power of JPA in order to create robust and flexible Java applications. With this Mini Book, you will get introduced to JPA and smoothly transition to more advanced concepts.

JVM Troubleshooting Guide

The Java virtual machine is really the foundation of any Java EE platform. Learn how to master it with this advanced guide!

Given email address is already subscribed, thank you!
Oops. Something went wrong. Please try again later.
Please provide a valid email address.
Thank you, your sign-up request was successful! Please check your e-mail inbox.
Please complete the CAPTCHA.
Please fill in the required fields.

One Response to "Java memes which refuse to die"

  1. Andrew Starovoyt says:

    If you use simple static field like “static Singleton instance = new Singleton(); ”
    there is no lazy loading

Leave a Reply


2 + = eleven



Java Code Geeks and all content copyright © 2010-2014, Exelixis Media Ltd | Terms of Use | Privacy Policy
All trademarks and registered trademarks appearing on Java Code Geeks are the property of their respective owners.
Java is a trademark or registered trademark of Oracle Corporation in the United States and other countries.
Java Code Geeks is not connected to Oracle Corporation and is not sponsored by Oracle Corporation.
Do you want to know how to develop your skillset and become a ...
Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you two of our best selling eBooks for FREE!

Get ready to Rock!
You can download the complementary eBooks using the links below:
Close