简体   繁体   中英

Modifying a static variable in non-synchronized static method, is there a danger to thread safety?

I have a class with a static method modifying a static variable as follows, does this method needs to be synchonized for thread safe operations ?

public final class IdManager {

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

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

Should this method have been synchronized?

Well it's certainly not safe as it is. Two threads could both read the value, but decrement their local copy, then both write. Badness.

You could synchronize it (and all other aspects to the variable) - but it would be better to use AtomicInteger which is designed for exactly this sort of thing. That's fine if the only shared state you're modifying is that one value; if you're trying to modify more shared state atomically (eg some "next ID" counter as well as the number of outstanding IDs) then you would need to either thing really, really carefully about the various interleavings, or use a synchronized block instead.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM