DZone
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
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones AWS Cloud
by AWS Developer Relations
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones
AWS Cloud
by AWS Developer Relations
The Latest "Software Integration: The Intersection of APIs, Microservices, and Cloud-Based Systems" Trend Report
Get the report
  1. DZone
  2. Coding
  3. Java
  4. Java Memes Which Refuse to Die

Java Memes Which Refuse to Die

Peter Lawrey user avatar by
Peter Lawrey
·
Aug. 23, 12 · Interview
Like (0)
Save
Tweet
Share
28.77K 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

  • Benefits and Challenges of Multi-Cloud Integration
  • What Is Docker Swarm?
  • Introduction to Cloud Native
  • 8 Proven Ways to Combat End-of-Life Software Risks

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • 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: