DZone
Java Zone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
  • Refcardz
  • Trend Reports
  • Webinars
  • Zones
  • |
    • Agile
    • AI
    • Big Data
    • Cloud
    • Database
    • DevOps
    • Integration
    • IoT
    • Java
    • Microservices
    • Open Source
    • Performance
    • Security
    • Web Dev
DZone > Java Zone > Java Memes Which Refuse to Die

Java Memes Which Refuse to Die

Peter Lawrey user avatar by
Peter Lawrey
·
Aug. 23, 12 · Java Zone · Interview
Like (0)
Save
Tweet
28.36K Views

Join the DZone community and get the full member experience.

Join For Free

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 interest 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

  1. 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)
  2. Similarly, you might believe that DataInputStream does something useful here when it doesn't
  3. 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 it is much simpler.
Java (programming language) Die (manufacturing)

Published at DZone with permission of Peter Lawrey, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • The 5 Healthcare AI Trends Technologists Need to Know
  • What Is ERP Testing? - A Brief Guide
  • Migrating From Heroku To Render
  • Real-Time Supply Chain With Apache Kafka in the Food and Retail Industry

Comments

Java Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • MVB Program
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends:

DZone.com is powered by 

AnswerHub logo