Modifying static variable in unsynchronized static method, is there a thread safety hazard?

I have a class with a static method modifying the static variable like this: does this method need to be synchronized for thread related operations?

public final class IdManager {

    private static int noOfIdsInReserveCurrently = 100;   
    private static final AtomicInteger allotedUserIdsCount; 

    public static int getNewId(){
         return allotedUserIdsCount.incrementAndGet();


Should this method be synchronized?


source to share

1 answer

Well, of course it's not safe as it is. The two threads could read the value, but shrink their local copy and then write. Badness.

You could sync it (and all other aspects to a variable), but it would be better to use AtomicInteger

one that is designed for exactly this kind of thing. It's fine if the only shared state you change is one value; if you are trying to modify the more split state atomically (eg some kind of "next id" counter and also the number of outstanding id's), you will either need to be really, very careful about the various interleaving, or use a synchronized block instead.



All Articles