HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavaMinor

Thread-Safe Integer Sequence

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
integerthreadsafesequence

Problem

I would like to give an Integer to whatever demands it. For that I use the following code

public class IntIDGenerator {

    private static int sequence = 1;

    public synchronized static int generate(){
        sequence++;
        return sequence;
    }

}


It is thread-safe because the synchronized term in the method generate(), but I have the feeling that it is possible to implement this generation in a better way. I was thinking in AtomicInteger, but I will have, more or less, the same problem. Any hint?

Solution

And what's wrong with :

public final class SDGIntIDGenerator {

    private static final AtomicInteger sequence = new AtomicInteger(1);

    private SDGIntIDGenerator() {}

    public static int generate(){
        return sequence.getAndIncrement();
    }

}


Atomic Integer is thread safe.

Put private constructor so no instances can be made.

Only static methods means helper class => make class final.

Edit :

While @bowmore is correct you could want more generators for each class, you could do the following :

public final class SDGIntIDGenerator {

    private static final ConcurrentHashMap mapper = new ConcurrentHashMap();

    private SDGIntIDGenerator () {}

    public static int generateId (Class _class) {
        mapper.putIfAbsent(_class, new AtomicInteger(1));
        return mapper.get(_class).getAndIncrement();
    }
}


With this implementation you could ask an id for each class.

This is because the ConcurrentHashMap is also thread safe for some methods.

Important note : Your generator will reset himself after server restart so usage for generating an id for storing in database is a bad idea.

You could also just return the AtomicInteger.

It doesn't matter if you are using a lot of threads and every thread knows that instance of the AtomicInteger.

The AtomicInteger will stay threadsafe.

Footnote : Wrote in java 6, with higher java you could refactor the instantiation of the ConcurrentHashMap.

Code Snippets

public final class SDGIntIDGenerator {

    private static final AtomicInteger sequence = new AtomicInteger(1);

    private SDGIntIDGenerator() {}

    public static int generate(){
        return sequence.getAndIncrement();
    }

}
public final class SDGIntIDGenerator {

    private static final ConcurrentHashMap<Class,AtomicInteger> mapper = new ConcurrentHashMap<Class,AtomicInteger>();

    private SDGIntIDGenerator () {}

    public static int generateId (Class _class) {
        mapper.putIfAbsent(_class, new AtomicInteger(1));
        return mapper.get(_class).getAndIncrement();
    }
}

Context

StackExchange Code Review Q#54641, answer score: 6

Revisions (0)

No revisions yet.