It is surprising how many useful classes can be found in java.util that are not commonly known to general public. Every now and then I stumble upon a class that has the functionality I have been implementing over and over my myself and today I will tell you about one of them: have you ever heard about java.util.concurrent.atomic package?

Before I will get into the details I’d like you to look at the following code snippet:

1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
public class MultiThreadedClass {
    private volatile int sharedValue = 0;

    public synchronized void resetSharedValue() {
        sharedValue = 0;
    }

    public synchronized int incrementSharedValue() {
        sharedValue++;
        return sharedValue;
    }

    // other code dealing with sharedValue...
}

Looks familiar? I remember many situations like that when I had to deal with synchronising the methods of a simple class just to make the access to one lousy variable thread safe. It is understandable to do that when you work with some complicated concurrency – in that case problem needs to be isolated and dealt with carefully. But when you deal with a one int value it just seems to be a waste of effort. It’s also a potential risk: class seems to be really simple, so other programmers may not pay enough attention and ‘forget’ to keep the access to the int variable always synchronised. What is more annying is that you lose a lot of performance on the synchronisation. You might say “well, that’s the way it is” but it feels so wrong to spend so much and gain so little…

So why am I telling you that? Because java.util.concurrent.atomic has a solution for that: AtomicInteger! As the name suggest the object of that class are thread safe (so you do not have to deal with synchronisation anymore) and guarantees that every operation done on it (by one of many helpful methods) will be atomic! What is more the class itself does not use any locking, so you do not get the performance hit of ’synchronized’ access methods!

Besides AtomicInteger java.util.concurrent.atomic package has many other classes that can deal with atomic access to references, arrays, booleans, longs… there is something for everyone:) Obviously this is not applicable everywhere, in more complex situations I usually prefer to do the synchronisation by myself just to be sure I’ll wont lose the control over it. Then again when its possible it is worth to go ATOMIC! If you’re not hooked yet, check out this article about the benefits of atomic classes and the performance gains.