Coming Up for Air

Be Careful with Statics

Thursday, July 16, 2015 |

I recently came across an interesting piece of code at work:

1
    private static final DateFormat DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd");

What struck me as odd was the private qualifier and that the fact that SimpleDateFormat is not thread-safe. Is the private some odd attempt to work around concurrency issues, or was thread safety just overlooked? That led me to this question: Is a private static still one instance per JVM, or does the private actually change anything? My understanding was that this was a bug, but I thought I’d write a test just to make sure.

Let’s start with a class:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
public class SomeClass {
    private static int number;

    public SomeClass(int number) {
        this.number = number;
    }

    public int getNumber() {
        return number;
    }
}

and here’s our simple test:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
public class StaticTest {
    public static void main(String[] args) {
        SomeClass a = new SomeClass(1);
        SomeClass b = new SomeClass(2);

        System.out.println("a.number = " + a.getNumber());
        System.out.println("b.number = " + b.getNumber());
    }

}

As expected, here’s the output:

1
2
a.number = 2
b.number = 2

If you’ve been around the block a few times, this probably doesn’t come as a surprise. If you’re newer, though, or haven’t ever had to give it thought, you might be mildly surprised. Either way, the bottom line is this: scope qualifiers don’t modify the behavior of a static, so if the type is not thread-safe, you’ll need a better (read as: correct) way to handle the concurrency concerns.

Search

    Quotes

    Sample quote

    Quote source

    About

    My name is Jason Lee. I am a software developer living in the middle of Oklahoma. I’ve been a professional developer since 1997, using a variety of languages, including Java, Javascript, PHP, Python, Delphi, and even a bit of C#. I currently work for Red Hat on the WildFly/EAP team, where, among other things, I maintain integrations for some MicroProfile specs, OpenTelemetry, Micrometer, Jakarta Faces, and Bean Validation. (Full resume here. LinkedIn profile)

    I am the president of the Oklahoma City JUG, and an occasional speaker at the JUG and a variety of technical conferences.

    On the personal side, I’m active in my church, and enjoy bass guitar, running, fishing, and a variety of martial arts. I’m also married to a beautiful woman, and have two boys, who, thankfully, look like their mother.

    My Links

    Publications